Simple Serilog

Install Packages

Install Serilog packages for your own project, run the command belows to install Serilog packages.

Package Manager

PM> Install-Package Serilog.Sinks.RollingFile -Version 3.3.0
PM> Install-Package Serilog.Extensions.Logging -Version 2.0.2
PM> Install-Package Serilog.Enrichers.Environment -Version 2.1.2
PM> Install-Package Serilog.Enrichers.Thread -Version 3.0.0
PM> Install-Package Serilog.Settings.Configuration -Version 2.4.0

.NET CLI

dotnet add package Serilog.Sinks.RollingFile --version 3.3.0
dotnet add package Serilog.Extensions.Logging --version 2.0.2
dotnet add package Serilog.Enrichers.Environment --version 2.1.2
dotnet add package Serilog.Enrichers.Thread --version 3.0.0
dotnet add package Serilog.Settings.Configuration --version 2.4.0

Configuration

Configure the Serilog in the appsettings.json in the section of “Serilog”:

{
  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "Logs\\log-{Date}.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{MachineName}][Thread:{ThreadId}] [{Level}] {SourceContext} - {Message}{NewLine}{Exception}"
        }
      }
    ]
  }
}

Serilog levels can be overridden per logging source as below, for example we only want to filter Microsoft and System category from Level Information and below.

Configure the serilog options in the Startup.cs with the Startup method:

Add the Serilog in ConfigureServices with the AddLogging extension method:

Using a Static Logger

Loggers are created using a static Logger object:

The example above will use a static logger that does not record events anywhere.

Using a Logger

Create an API controller TestsController.cs. We now are injecting an instance of ILogger. Of which we are using to Logging inside our Get() method.

Update the TestsController class with the following.

Much like TestsController.cs we inject an instance of ILogger and perform logging inside of GET request.

If we run our app now and consume the API endpoint http://localhost/api/tests, we should end up with some logging results in the console.

Create a Logger Extensions

This is an optional extension for logger to define custom logging messages.

Resources

Last updated

Was this helpful?