将EntityFrameworkCore生成的SQL语句输出到控制台,使用hangfire

将EntityFrameworkCore生成的SQL语句输出到控制台

参考文档如下

EF Core 日志记录要求使用一个或多个日志记录提供程序配置的 ILoggerFactory。
日志记录-EF Core | Microsoft Docs

安装适当的包后,应用程序应创建 Server.loggerfactory 的单一实例/全局实例。 例如,使用控制台记录器:

public static readonly ILoggerFactory MyLoggerFactory
    = LoggerFactory.Create(builder => { builder.AddConsole(); });

然后,应该在 DbContextOptionsBuilder 上向 EF Core 注册此单一实例/全局实例。 例如:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");

筛选记录内容

应用程序可以通过在 ILoggerProvider 上配置筛选器来控制要记录的内容。 例如:

public static readonly ILoggerFactory MyLoggerFactory
    = LoggerFactory.Create(builder =>
        {
            builder
                .AddFilter((category, level) =>
                    category == DbLoggerCategory.Database.Command.Name
                    && level == LogLevel.Information)
                .AddConsole();
        });

abp中使用

选择 .EntityFrameworkCore 项目
找到
DbContext

添加如下代码

        public static readonly ILoggerFactory MyLoggerFactory
            = LoggerFactory.Create(builder =>
            {
                builder
                    .AddFilter((category, level) =>
                        category == DbLoggerCategory.Database.Command.Name
                        && level == LogLevel.Information)
                    .AddConsole();
            });

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseLoggerFactory(MyLoggerFactory)
                .EnableSensitiveDataLogging(true);

使用 Hangfire

添加nuget 包 Hangfire ...

getting-started Hangfire

  • 找到并修改 **HttpApiHostModule
    在 Startup.cs 直接进入
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Volo.Abp;

namespace MyBookStore
{
    public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddApplication(options =>
            {
                options.UseAutofac();
            });

            return services.BuildServiceProviderFromFactory();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            app.InitializeApplication();
        }
    }
}
  • 添加使用的Configure
        private void ConfigureHangfire(ServiceConfigurationContext context, IConfigurationRoot Configuration)
        {
            // https://github.com/marcoCasamento/Hangfire.Redis.StackExchange
            context.Services.AddHangfire(configuration =>
            {
                configuration.UseRedisStorage(Configuration["Redis:Configuration"]);
            });

            ////https://github.com/perrich/Hangfire.MemoryStorage
            //context.Services.AddHangfire(config =>
            //{
            //    config.UseMemoryStorage();
            //});

            // https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html
            //// Add Hangfire services. 
            //context.Services.AddHangfire(configuration => configuration
            //    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            //    .UseSimpleAssemblyNameTypeSerializer()
            //    .UseRecommendedSerializerSettings()
            //    .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
            //    {
            //        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            //        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            //        QueuePollInterval = TimeSpan.Zero,
            //        UseRecommendedIsolationLevel = true,
            //        UsePageLocksOnDequeue = true,
            //        DisableGlobalLocks = true
            //    }));
            // Add the processing server as IHostedService
            context.Services.AddHangfireServer();

            context.Services.AddTransient();
        }
  • 使用 Hangfire
    public class HangfireService
    {
        private readonly ILibraryService _service;

        public HangfireService(ILibraryService service)
        {
            _service = service;
        }

        public async Task AddLibraryDto(LibraryDto model)
        {
            Console.WriteLine($"HangfireService 开始 在:{DateTime.Now.ToLongTimeString()} 启动");
            await _service.AddLibraryDto(model);
            Console.WriteLine($"HangfireService 结束 在:{DateTime.Now.ToLongTimeString()}");
        }

        //private IServiceProvider serviceProvider { get; }
        //public HangfireService(IServiceProvider _serviceProvider)
        //{
        //    serviceProvider = _serviceProvider;
        //}
        //public async Task AddLibraryDto(LibraryDto model)
        //{
        //    Console.WriteLine($"HangfireService 开始 在:{DateTime.Now.ToLongTimeString()} 启动");
        //    using (var serviceScope = serviceProvider.GetService().CreateScope())
        //    {
        //        var service = serviceScope.ServiceProvider.GetService();
        //        await service.AddLibraryDto(model);
        //    }
        //    Console.WriteLine($"HangfireService 结束 在:{DateTime.Now.ToLongTimeString()}");
        //}
    }
  • test
        [HttpGet("AddLibrary")]
        public async Task AddLibrary()
        {
            try
            {
                var watch = new Stopwatch();
                watch.Start();//开始计时
                Console.WriteLine($"LibraryController 开始 在:{DateTime.Now.ToLongTimeString()} 启动");

                Thread.Sleep(1000);
                var dto = new LibraryDto
                {
                    Name = "添加一条",
                    Address = "1号"
                };
                var model = await _service.AddLibraryDto(dto);

                Console.WriteLine($"LibraryController 结束 在:{DateTime.Now.ToLongTimeString()}");
                watch.Stop();//停止计时
                Console.WriteLine("耗时:" + (watch.ElapsedMilliseconds));//输出时间 毫秒
                var watch2 = new Stopwatch();
                watch2.Start();//开始计时

                for (var i = 0; i < 1000; i++)
                {
                    BackgroundJob.Enqueue(jobs => jobs.AddLibraryDto(model));
                    //var jobId = BackgroundJob.Enqueue(
                    //    () => _hangfireService.AddLibraryDto(model));
                }



                watch2.Stop();//停止计时
                Console.WriteLine("hangfire 耗时:" + (watch2.ElapsedMilliseconds));//输出时间 毫秒
                return model;
            }
            catch (Exception ex)
            {
                return new LibraryDto
                {
                    Name = ex.Message
                };
            }

        }
  • 打开浏览器 localhost:*/hangfire

你可能感兴趣的:(将EntityFrameworkCore生成的SQL语句输出到控制台,使用hangfire)