zoukankan      html  css  js  c++  java
  • 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);
                });
    复制代码

    运行 得到效果如图:

  • 相关阅读:
    SpringBoot学习历程
    日期和时间库Joda Time
    apache commons validator
    apache commons fileupload
    apache commons io
    apache commons compress
    apache commons codec
    apache commons email
    Http协议介绍
    Java原生Socket API
  • 原文地址:https://www.cnblogs.com/Justsoso-WYH/p/9560577.html
Copyright © 2011-2022 走看看