NET5 EF Core添加EF生成SQL日志记录

1、添加NuGet包:Microsoft.Extensions.Logging.Debug

2、添加单独类库用于后期维护:BCode.DataBase.Log

3、添加EFCoreLoggerProvider类

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

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

4、添加EFCoreLogger类

using Microsoft.Extensions.Logging;
using System;

namespace BCode.DataBase.Log
{
    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);
                Console.WriteLine(logContent);
            }
        }

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

5、在DBContext中注入日志记录

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new EFCoreLoggerProvider());
            //添加EnableSensitiveDataLogging,启用敏感数据记录
            optionsBuilder.UseMySQL(_connectionString).UseLoggerFactory(loggerFactory).EnableSensitiveDataLogging();
        }

  

  

 

posted @ 2020-12-09 14:54  马永猛  阅读(1007)  评论(0编辑  收藏  举报