1. 程式人生 > 實用技巧 >NET5 EF Core新增EF生成SQL日誌記錄

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