Serilog - program.cs

Here is a sample stripped down program.cs with configurations in place for Serilog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using Serilog;


// serilog stuff - see
// https://codewithmukesh.com/blog/structured-logging-with-serilog-in-aspnet-core/
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();

try
{
var builder = WebApplication.CreateBuilder(args);

//more serilog
// add Serilog to our ASP.NET Core Application’s DI Container. We
// have defined 2 configurations here, which are to write to Console,
// and to read configurations from appsettings.json. This will be
// applied to the entire application wherever we use the
// ILogger<> interface. Also, this will ignore the Logging configuration
// from the appsettings file and consider only the Serilog section in
// appsettings.json.
//
builder.Host.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext() // from copilot
.WriteTo.Console());

// get appSettings.json data
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

// load up the config file, load AppSettings.json and the environment specific one.
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", true, reloadOnChange: true)
.Build();


var app = builder.Build();
// serilog - to log ASP.NET Core HTTP requests to the sinks.
app.UseSerilogRequestLogging();


app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "server terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}

I’ve documented this, more text will be supplied as needed.