由于EFCore并没直接生成脚本到txt文件,故而自己画了点时间把实现记录下来,方便给大家参考。
0.安装Microsoft.Extensions.Logging.Debug,我这里是2.1.1版本。
1.新建一个EFCoreDatabaseCmdLog在abp的Core层下,
using Abp.Dependency; using Castle.Core.Logging; namespace SensorBroker.Log { public static class EFCoreDatabaseCmdLog { public static ILogger Logger { get; private set; } static EFCoreDatabaseCmdLog() { Logger = IocManager.Instance.IsRegistered(typeof(ILoggerFactory)) ? IocManager.Instance.Resolve().Create(typeof(EFCoreDatabaseCmdLog)) : NullLogger.Instance; } public static void Debug(string logContent) { Logger.Debug(logContent); } } }
2.在abp.EntityFrameworkCore层EntityFrameworkCore文件夹下新增2个文件EFLoggerProvider.cs与EFLogger.cs
EFLogger.cs
using Microsoft.Extensions.Logging; using System; namespace SensorBroker.EntityFrameworkCore { public class EFLogger : ILogger { private readonly string categoryName; public EFLogger(string categoryName) => this.categoryName = categoryName; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { //ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command" && logLevel == LogLevel.Information) { var logContent = formatter(state, exception); XXXXX.Log.EFCoreDatabaseCmdLog.Debug(logContent);//xxxx 需要替换成自己的项目名字 } } public IDisposable BeginScope (TState state) => null; } }
EFLoggerProvider
using Microsoft.Extensions.Logging; namespace SensorBroker.EntityFrameworkCore { public class EFLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName); public void Dispose() { } } }
3.修改SensorBrokerDbContextConfigurer.cs文件如下,我这里用的是mysql,请酌情参考。
using System.Data.Common; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace SensorBroker.EntityFrameworkCore { public static class SensorBrokerDbContextConfigurer { public static void Configure(DbContextOptionsBuilderbuilder, string connectionString) { var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new EFLoggerProvider()); builder.UseMySql(connectionString); builder.UseLoggerFactory(loggerFactory); builder.EnableSensitiveDataLogging(); } public static void Configure(DbContextOptionsBuilder builder, DbConnection connection) { var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new EFLoggerProvider()); builder.UseMySql(connection); builder.UseLoggerFactory(loggerFactory); builder.EnableSensitiveDataLogging(); } } }
4.修改配置log4net.config
在log4net节点中增加如下配置
这样所有的数据库脚本日志都就会到EFLogs.txt中。