Code
·
44 lines
·
1745 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Channels;
namespace VanDerHeijden.Logging.File;
/// <summary>
/// Extension methods for registering file-based logging via <see cref="ILoggingBuilder"/>.
/// </summary>
public static class FileLoggingBuilderExtensions
{
/// <summary>
/// Adds a file logger that writes log messages to daily rotating text files inside
/// <paramref name="logDirectory"/>.
/// </summary>
/// <param name="builder">The <see cref="ILoggingBuilder"/> to configure.</param>
/// <param name="logDirectory">
/// Path to the directory where log files are written.
/// The directory is created automatically if it does not exist.
/// Defaults to <c>"Logs"</c>.
/// </param>
/// <returns>The <paramref name="builder"/> so that additional calls can be chained.</returns>
public static ILoggingBuilder AddFileLogger(this ILoggingBuilder builder, string logDirectory = "Logs")
{
builder.Services.AddSingleton<ILoggerProvider>(sp =>
{
var httpContextAccessor = sp.GetService<IHttpContextAccessor>();
var logWriter = new FileLogWriter(logDirectory);
var batchedLogger = new BatchedLogger<string>(logWriter, fullMode: BoundedChannelFullMode.Wait);
return new BatchedLoggerProvider<string>(
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;
}
}