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

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM