using APT.Infrastructure.Core; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; namespace APT.Infrastructure.EF { public class EFDbContextLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) => new EFDbContextLogger(categoryName); public void Dispose() { } } public class EFDbContextLogger : ILogger { private readonly string categoryName; public EFDbContextLogger(string categoryName) => this.categoryName = categoryName; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { //ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command") { var logContent = formatter(state, exception); LoggerManager.GetLogger("SQLLog"). Info(logContent + System.Environment.NewLine + (exception != null ? ("Except:" + exception.Message) : string.Empty)); } } public IDisposable BeginScope(TState state) => null; } }