Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
Matthew Flynn Avatar asked Sep 17 '25 07:09

Matthew Flynn


2 Answers

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));
like image 147
Sk Shahnawaz-ul Haque Avatar answered Sep 19 '25 23:09

Sk Shahnawaz-ul Haque


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))
like image 40
Liam Kernighan Avatar answered Sep 19 '25 21:09

Liam Kernighan