using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Channels;
namespace VanDerHeijden.Logging.File;
///
/// Extension methods for registering file-based logging via .
///
public static class FileLoggingBuilderExtensions
{
///
/// Adds a file logger that writes log messages to daily rotating text files inside
/// .
///
/// The to configure.
///
/// Path to the directory where log files are written.
/// The directory is created automatically if it does not exist.
/// Defaults to "Logs".
///
/// The so that additional calls can be chained.
public static ILoggingBuilder AddFileLogger(this ILoggingBuilder builder, string logDirectory = "Logs")
{
builder.Services.AddSingleton(sp =>
{
var httpContextAccessor = sp.GetService();
var logWriter = new FileLogWriter(logDirectory);
var batchedLogger = new BatchedLogger(logWriter, fullMode: BoundedChannelFullMode.Wait);
return new BatchedLoggerProvider(
batchedLogger,
entryFactory: (category, message, _, exception, ctx) =>
{
var http = ctx is null ? "" : $" [{ctx.Method} {ctx.Path} {ctx.ClientIp}]";
var ex = exception is null ? "" : $"{Environment.NewLine}{exception}";
return $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}{http} [{category}] {message}{ex}{Environment.NewLine}";
},
httpContextAccessor
);
});
return builder;
}
}