【EFCore】日志记录执行的SQL语句

EF Core 3.1

1.新建EFCoreLogger类,继承ILogger

public class EFCoreLogger : ILogger
{
    private readonly string categoryName;

    public EFCoreLogger(string categoryName) => this.categoryName = categoryName;

    public bool IsEnabled(LogLevel logLevel) => true;

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        //EF Core执行SQL语句时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
        if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command" && logLevel == LogLevel.Information)
        {
            var logContent = formatter(state, exception);
            //写入文本中
            LogHelper.Log("SqlLog", "【SQL语句】:" + logContent);
        }
    }

    public IDisposable BeginScope<TState>(TState state) => null;
}

2.新建EFCoreLoggerProvider,继承ILoggerProvider

public class EFCoreLoggerProvider : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName) => new EFCoreLogger(categoryName);
    public void Dispose() { }
}

3.在DbContext的OnConfiguring方法,设置日志写入

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var loggerFactory = new LoggerFactory();
    loggerFactory.AddProvider(new EFCoreLoggerProvider());

    optionsBuilder.UseSqlServer(ConnectionString).UseLoggerFactory(loggerFactory);
}

看看,效果

成功了,但是,参数都是?,添加EnableSensitiveDataLogging即可,启用敏感数据记录

 optionsBuilder.UseSqlServer(ConnectionString).UseLoggerFactory(loggerFactory).EnableSensitiveDataLogging();

现在参数了

 

参考:

https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/logging?tabs=v3

https://docs.microsoft.com/zh-cn/archive/msdn-magazine/2018/october/data-points-logging-sql-and-change-tracking-events-in-ef-core

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页