47 lines
1.4 KiB
C#
47 lines
1.4 KiB
C#
using Flawless.Server.Models;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
|
|
namespace Flawless.Server.Services;
|
|
|
|
public class DatabaseLoggerProvider(IServiceProvider serviceProvider) : ILoggerProvider
|
|
{
|
|
public ILogger CreateLogger(string categoryName)
|
|
{
|
|
// 过滤非业务错误日志
|
|
if (!categoryName.StartsWith("Flawless.Server")) return NullLogger.Instance;
|
|
return new DatabaseLogger(serviceProvider.CreateScope());
|
|
}
|
|
|
|
public void Dispose() { }
|
|
}
|
|
|
|
public class DatabaseLogger(IServiceScope scope) : ILogger
|
|
{
|
|
private readonly AppDbContext _dbContext = scope.ServiceProvider.GetService<AppDbContext>()!;
|
|
|
|
public IDisposable? BeginScope<TState>(TState state) => scope;
|
|
|
|
public bool IsEnabled(LogLevel logLevel) => true;
|
|
|
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
|
Func<TState, Exception?, string> formatter)
|
|
{
|
|
try
|
|
{
|
|
_dbContext.SystemLogs.Add(new SystemLog
|
|
{
|
|
LogLevel = logLevel,
|
|
Message = formatter(state, exception),
|
|
Exception = exception?.ToString(),
|
|
Timestamp = DateTime.UtcNow,
|
|
Source = eventId.Name
|
|
});
|
|
|
|
_dbContext.SaveChanges();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.Error.WriteLine("Cannot save logfile into database: " + e);
|
|
}
|
|
}
|
|
} |