Code
·
56 lines
·
2139 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
44
45
46
47
48
49
50
51
52
53
54
55
56using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System.Threading.Channels;
namespace VanDerHeijden.Logging.Redis;
/// <summary>
/// Extension methods for registering Redis-based logging via <see cref="ILoggingBuilder"/>.
/// </summary>
public static class RedisLoggingBuilderExtensions
{
/// <summary>
/// Adds a Redis logger that pushes log entries as JSON to a Redis list using <c>RPUSH</c>.
/// </summary>
/// <param name="builder">The <see cref="ILoggingBuilder"/> to configure.</param>
/// <param name="database">The Redis database instance used for all write operations.</param>
/// <param name="listKey">The Redis key of the list that receives log entries. Defaults to <c>"logs"</c>.</param>
/// <param name="ttl">
/// Optional time-to-live applied to <paramref name="listKey"/> after each batch write.
/// When <see langword="null"/> (the default) the key never expires.
/// </param>
/// <returns>The <paramref name="builder"/> so that additional calls can be chained.</returns>
public static ILoggingBuilder AddRedisLogger(
this ILoggingBuilder builder,
IDatabase database,
string listKey = "logs",
TimeSpan? ttl = null)
{
builder.Services.AddSingleton<ILoggerProvider>(sp =>
{
var httpContextAccessor = sp.GetService<IHttpContextAccessor>();
var logWriter = new RedisLogWriter(database, listKey, ttl);
var batchedLogger = new BatchedLogger<RedisLogEntry>(logWriter, batchSize: 200, maxIdleMs: 2000, fullMode: BoundedChannelFullMode.DropOldest);
return new BatchedLoggerProvider<RedisLogEntry>(
batchedLogger,
entryFactory: (category, message, logLevel, exception, ctx) => new RedisLogEntry
{
Timestamp = DateTime.UtcNow,
Level = logLevel.ToString(),
Category = category,
Message = message,
Exception = exception?.ToString(),
Path = ctx?.Path,
Method = ctx?.Method,
ClientIp = ctx?.ClientIp,
Referer = ctx?.Referer,
UserAgent = ctx?.UserAgent
},
httpContextAccessor
);
});
return builder;
}
}