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