Configure Serilog with WebApplicationBuilder in Net 6
Asked Answered
S

2

7

I Net Core 5 I used to configure Serilog using the recommended approach:

public static void Main(string[] args) {

  Log.Logger = new LoggerConfiguration().WriteTo.Console().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>(); });

How to configure Serilog in Net 6 using WebApplicationBuilder:

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog

var app = builder.Build();
Shikoku answered 27/11, 2021 at 16:3 Comment(0)
I
12

You can still use the same extension method on Host.

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog();

var app = builder.Build();
Illyrian answered 27/11, 2021 at 16:23 Comment(0)
P
6

To expand a bit on Kahbazi's answer:

If you want to configure with your appsetting.json files, you'll need to install Nuget package Serilog.AspNetCore and put this code in Program.cs:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((hostContext, services, configuration) =>
{
    configuration.ReadFrom.Configuration(hostContext.Configuration);
});

// ...

var app = builder.Build();

// ...

app.Run();

and this code in appsettings.json:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Verbose",
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "Console"
      }
    ]
  },
 "YourCustomConfigKey1": "blahblah",
 "YourCustomConfigKey2": "asdf"
}
Pedestrianize answered 14/6, 2022 at 20:20 Comment(1)
Thank you for that snippet in Program.cs, that was the missing piece for me.Acidforming

© 2022 - 2024 — McMap. All rights reserved.