EF Core 日志跟踪sql语句

2018/08/30 15:43
阅读数 7

EF Core 日志跟踪sql语句

官方文档链接:https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging

1.新增自定义ILoggerProvider实现类

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

2.新增自定义日志处理接口ILogger的实现

复制代码
public class EFLogger : ILogger
    {
        private readonly string categoryName;

        public EFLogger(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执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
            if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command"
                    && logLevel == LogLevel.Information) {
                var logContent = formatter(state, exception);
                //TODO: 拿到日志内容想怎么玩就怎么玩吧
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(logContent);
                Console.ResetColor();
            }
        }

        public IDisposable BeginScope<TState>(TState state) => null;
    }
复制代码

3.配置DbContext的日志记录

方式一,在DbContext的OnConfiguration中配置

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new EFLoggerProvider());
            optionsBuilder.UseLoggerFactory(loggerFactory);
            base.OnConfiguring(optionsBuilder);
        }

方式二(AspNet Core),在Startup的ConfigureService中配置

复制代码
services.AddDbContext<YourDbContext>(r => {
                //使用ef core mysql 连接
                var loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(new EFLoggerProvider());

                r.UseMySQL(Configuration.GetConnectionString("your db connection string"))
                    .UseLoggerFactory(loggerFactory);
            });
复制代码

 

运行 得到效果如图:

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部