public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, SomeDbContext db)
{
...
loggerFactory.AddProvider(new DbLoggerProvider(db));
...
{
public class DbLoggerProvider: ILoggerProvider
{
private SomeDbContext _db;
public DbLoggerProvider(SomeDbContext db)
{
_db = db;
}
public void Dispose()
{
}
public ILogger CreateLogger(string categoryName)
{
return new DbLogger(_db);
}
}
public class DbLogger: ILogger
{
private const LogLevel _minLevel = LogLevel.Debug;
private SomeDbContext _db;
public DbLogger(SomeDbContext db)
{
_db = db;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (formatter == null) return;
try
{
_db.Logs.Add(/*Some log data*/);
_db.SaveChanges();
}
catch (Exception e)
{
// ignored
}
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= _minLevel;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
}
loggerFactory.AddProvider(new DbLoggerProvider(app.ApplicationServices));
using (var scope = _serviceProvider.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<CuDb>();
db.Logs.Add(new CheckUpDb.Log() { Date = DateTime.UtcNow, LogLevel = logLevel, Message = formatter(state, exception) });
db.SaveChanges();
}