• EF Core 日志跟踪sql语句


    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);
                });

    运行 得到效果如图:

  • 相关阅读:
    严格模式
    es6模块与 commonJS规范的区别
    Javascript内置对象、原生对象、宿主对象关系
    实现继承的几种方式
    创建对象的一些方式
    null的小扩展
    getElementById的缩略
    你真的知道为什么不推荐使用@import?
    换行与不换行
    transition与animation
  • 原文地址:https://www.cnblogs.com/gucaocao/p/9050981.html
Copyright © 2020-2023  润新知