Serilog is not logging logs from Program.cs

175 views Asked by At

I've updated my .NET 5 application to .NET 6 and encountered a logging issue. In Program.cs Everything above the line var app = builder.Build(); is being logged to the console, while anything below that line isn't getting logged to either the console or the text file. I suspect this is because the configuration from appsettings.json takes effect after calling Build(), and in appsettings.json the default log level is set to Error. Although I've set an override for "DefaultNameSpace.Program":"Information" in appsettings.json, it doesn't seem to be working for the logs in Program.cs.

The DefaultNameSpace is the namespace that is set in project settings.

enter image description here

In . NET 6, you no longer need to write out the Program class and Main method. What would be the correct namespace for Program class?

program.cs

// The initial "bootstrap" logger is able to log errors during start-up. It's completely replaced by the
// logger configured in `UseSerilog()` below, once configuration and dependency-injection have both been
// set up successfully.
Log.Logger = new LoggerConfiguration()    
    .WriteTo.Console()
    .CreateBootstrapLogger();

Log.Information("Starting up!");

try
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog((context, services, configuration) => configuration
                .ReadFrom.Configuration(context.Configuration));

    builder.WebHost.UseUrls("http://*:40004");    

    Log.Information("Building application.");

    // Information logs above this line are logged
    var app = builder.Build();

    // Information logs below are not getting logged        
    Log.Information("Running application");

    app.Run();

    Log.Information("Application Started");
}
catch (Exception ex)
{
    Log.Fatal(ex, "An unhandled exception occurred during bootstrapping");
}
finally
{
    Log.CloseAndFlush();
}

appsettings.json

"Serilog": {
  "Using": [ "Serilog.Sinks.Console","Serilog.Sinks.File" ],
  "MinimumLevel": {
    "Default": "Error",
    "Override": {
      "Microsoft": "Warning",        
      "MyNameSpace.Program": "Information"
    }
  },
  "WriteTo": [
    {
      "Name": "Console"
    },
    {
      "Name": "File",
      "Args": {
        "path": "C:\\Logs\\UI.txt",
        "fileSizeLimitBytes": "10485760",
        "rollingInterval": "Day",
        "rollOnFileSizeLimit": true
      }
    }
  ]
},
0

There are 0 answers