ABP增加记录EFCore 生成数据库脚本日志到新的txt文件

时间:2021-10-31 04:27:05

由于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<ILoggerFactory>().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<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);
                XXXXX.Log.EFCoreDatabaseCmdLog.Debug(logContent);//xxxx 需要替换成自己的项目名字
            }
        }

        public IDisposable BeginScope<TState>(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(DbContextOptionsBuilder<SensorBrokerDbContext> builder, string connectionString)
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new EFLoggerProvider());
            builder.UseMySql(connectionString);
            builder.UseLoggerFactory(loggerFactory);
            builder.EnableSensitiveDataLogging();
        }

        public static void Configure(DbContextOptionsBuilder<SensorBrokerDbContext> builder, DbConnection connection)
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new EFLoggerProvider());
            builder.UseMySql(connection);
            builder.UseLoggerFactory(loggerFactory);
            builder.EnableSensitiveDataLogging();
        }
    }
}

4.修改配置log4net.config

在log4net节点中增加如下配置

<appender name="EntityFrameworkCoreDatabaseCommandLogFile" type="log4net.Appender.RollingFileAppender" >
    <file value="App_Data/Logs/EFLogs.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10000KB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level