using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Channels;
namespace VanDerHeijden.Logging.Sql;
///
/// Extension methods for registering SQL Server-based logging via .
///
public static class SqlLoggingBuilderExtensions
{
///
/// Adds a SQL Server logger that bulk-inserts log entries into the specified table using SqlBulkCopy.
///
/// The to configure.
/// The SQL Server connection string.
///
/// The destination table name. Defaults to "Logs".
/// See for the expected schema.
///
/// The so that additional calls can be chained.
public static ILoggingBuilder AddSqlLogger(
this ILoggingBuilder builder,
string connectionString,
string tableName = "Logs")
{
builder.Services.AddSingleton(sp =>
{
var httpContextAccessor = sp.GetService();
var logWriter = new SqlLogWriter(connectionString, tableName);
var batchedLogger = new BatchedLogger(logWriter, batchSize: 200, maxIdleMs: 4000, fullMode: BoundedChannelFullMode.Wait);
return new BatchedLoggerProvider(
batchedLogger,
entryFactory: (category, message, logLevel, exception, ctx) => new SqlLogEntry
{
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;
}
}