using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using System.Threading.Channels;
namespace VanDerHeijden.Logging.MongoDb;
///
/// Extension methods for registering MongoDB-based logging via .
///
public static class MongoDbLoggingBuilderExtensions
{
///
/// Adds a MongoDB logger that inserts log entries into the specified collection in batches.
///
/// The to configure.
/// The MongoDB collection that will receive documents.
/// The so that additional calls can be chained.
public static ILoggingBuilder AddMongoDbLogger(this ILoggingBuilder builder, IMongoCollection collection) =>
builder.AddMongoDbLogger(_ => collection);
///
/// Adds a MongoDB logger that resolves the collection from the DI container at startup.
/// Use this overload when is already registered as a service.
///
/// The to configure.
///
/// A factory that receives the and returns the
/// to write log entries to.
///
/// The so that additional calls can be chained.
public static ILoggingBuilder AddMongoDbLogger(this ILoggingBuilder builder, Func> collectionFactory)
{
builder.Services.AddSingleton(sp =>
{
var httpContextAccessor = sp.GetService();
var logWriter = new MongoDbLogWriter(collectionFactory(sp));
var batchedLogger = new BatchedLogger(logWriter, batchSize: 100, maxIdleMs: 3000, fullMode: BoundedChannelFullMode.DropOldest);
return new BatchedLoggerProvider(
batchedLogger,
entryFactory: (category, message, logLevel, exception, ctx) => new LogEntry
{
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;
}
}