Shorts Series – Add or Enable Serilog in ASP.NET Core 7.0

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://www.talkingdotnet.com/add-or-enable-serilog-in-asp-net-core-7-0/

Serilog is a third-party, open-source structured logging library. It provides diagnostic logging to files, the console, and elsewhere. It is easy to set up, has a clean API, and is portable between recent .NET platforms. In the ASP.NET Core framework, Serilog has emerged as a popular logging library due to its flexibility, extensibility, and ease of use. In continuation with Shorts Series, here is a another very short post to add or enable Serilog in ASP.NET Core 7.0 application.

Follow these simple steps to add or enable Serilog in ASP.NET Core 7.0 application.

1. Install the Serilog NuGet Package

Install the following Nuget package, either via package manager console,

Install-Package Serilog.AspNetCore

Or, via Nuget Package manager.

Add or Enable Serilog in ASP.NET Core 7.0

2. Register Serilog

Next, open program.cs and register serilog.

// Add services to the container.
builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));

Also, register the pipeline.

app.UseSerilogRequestLogging();

3. Configure the settings in appsetting.json

Open appsetting.json file and add following code.

 "Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "/logs/log-.txt",
          "rollOnFileSizeLimit": true,
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter,Serilog.Formatting.Compact",
          "rollingInterval": "Day"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithThreadId", "WithMachineName" ]

Here, we are specifying to add logs to dotnet console and also into a .txt file which will be created under c:\logs folder. The following line "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ], defines where to log.

Instead of .txt, you can also write to .json. To do that, change the file extension in the above code.

4. Finally, lets start logging

Open your controller and start logging. Like,

[HttpGet]
[EnableQuery]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogInformation("WeatherForecast get method Starting.");
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

Make sure, logger in injected in your controller. Like,

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}

Run your app now and you should see these.