using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using StackExchange.Redis; using System.Threading.Channels; namespace VanDerHeijden.Logging.Redis; /// /// Extension methods for registering Redis-based logging via . /// public static class RedisLoggingBuilderExtensions { /// /// Adds a Redis logger that pushes log entries as JSON to a Redis list using RPUSH. /// /// The to configure. /// The Redis database instance used for all write operations. /// The Redis key of the list that receives log entries. Defaults to "logs". /// /// Optional time-to-live applied to after each batch write. /// When (the default) the key never expires. /// /// The so that additional calls can be chained. public static ILoggingBuilder AddRedisLogger( this ILoggingBuilder builder, IDatabase database, string listKey = "logs", TimeSpan? ttl = null) { builder.Services.AddSingleton(sp => { var httpContextAccessor = sp.GetService(); var logWriter = new RedisLogWriter(database, listKey, ttl); var batchedLogger = new BatchedLogger(logWriter, batchSize: 200, maxIdleMs: 2000, fullMode: BoundedChannelFullMode.DropOldest); return new BatchedLoggerProvider( 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; } }