Author : MD TAREQ HASSAN

From appsettings json

appsettings.json

{
    "Serilog": {
      "Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async"],
      "MinimumLevel": "Debug",
      "WriteTo": [
        { "Name": "Console" },
        { "Name": "File", "Args": { "path": "C:\\logs\\fooapp.log" } }
      ]
      "Enrich": [],
      "Destructure": [],
      "Properties": {
      }
    }
}

Creating logger

public static int Main(string[] args)
{

    var currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
	
    //Build Config
    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{currentEnv}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();
    
    //Configure logger
    Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
}

Logging

Log.Verbose("This is a verbose statement");
Log.Debug("This is a debug statement");
Log.Information("This is a info statement");
Log.Warning("This is a warning statement");
Log.Error(new IndexOutOfRangeException(), "This is an error statement");
Log.Fatal(new AggregateException(), "This is an fatal statement");

Using fluent API

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .WriteTo.File(@"C:\logs\fooapp.txt")
    .CreateLogger();

Note:
Log.CloseAndFlush() needs to be called once in a console application, before the application exits. It’s a “shutdown” method that ensures any buffered events are processed before the application exits.

Log.CloseAndFlush();

See: Lifecycle of Loggers