简体   繁体   中英

Configuring Serilog ASP.Net Core 3.2 with EF Core to log SQL statments

Previously when using the Microsoft.Extensions.Logging I would inject the ILoggerFactory and .UseLoggingFactory() when setting up my DbContext as follows (reduced for brevity);

    private readonly ILoggerFactory LoggerFactory;


    public Startup(... ILoggerFactory loggerFactory)
    {
        LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration.GetConnectionString($"DbDataContext");

        services.AddDbContext<OakfieldLeasingDataContext>(
            options => options
                .UseSqlServer(
                    connectionString,
                    x => x.UseNetTopologySuite())
                .UseLoggerFactory(LoggerFactory));
     }

I am trying to now swap in Serilog , I have successfully changed my Program.cs as follows;

    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Console(new RenderedCompactJsonFormatter())
        .WriteTo.File(new RenderedCompactJsonFormatter(), "./logs/log.ndjson")
        .CreateLogger();

        try
        {
            Log.Information("Starting up");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Application start-up failed");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseSerilog() 
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

and can successfully confirm the log is going to the log file. However, with the existing code I get the following error;

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'Blazor.Server.Startup'.

Can anyone advise how I can inject the Serilog LoggerFactory to EF Core to log the SQL generation please?

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Information)
                    .WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose))

You need to include the DB context in the following way:

services.AddDbContext<OakfieldLeasingDataContext>(
        options => options
            .UseSqlServer(
                connectionString,
                x => x.UseNetTopologySuite())
            .LogTo(Log.Logger.Information, LogLevel.Information, null));

From 3.0 There is a limit the types you can inject in to Startup. It was a misleading feature because it used a completely separate DI container to the rest of the app. You can still inject ILogger<T> in to your Configure method directly, but no longer in to the constructor or ConfigureServices

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {

In your dbcontext class you can use like this.

ILogger<DBContextClass> _logger;
        public DBContextClass(ILogger<EngageAPIController> logger)
        {               
            _logger = logger;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM