How To Implement Serilog In ASP.NET Core Web API

August 25, 2023
ASP.NET Core Web API

“The SeriLog library is one of the most popular and widely used logging libraries among developers of a Microsoft ASP.NET application a number of advantages distinguish it from other logging libraries available on the market.”

What is the definition of logging?

Every application needs logging to function properly. It assists in diagnosing and troubleshooting issues as well as helping developers understand what’s happening in the application.

Why should you consider Serilog?

Extensibility

Serilog contains more than 90 given sinks and is extremely expandable, including well-known logging services like Azure Blob Storage

  • Azure Blob Storage
  • Azure CosmosDB
  • Elasticsearch
  • PostgreSQL
  • SQLite
  • SQL Server and so on

Developers can add unique enrichers and sinks to the library by using the sophisticated plug-in architecture that Serilog offers. Sinks for common use like file and console sinks are part of it. The following example shows you how to log messages to a file and on the console.

  • Describe the activities that led up to an event in a breadcrumb trail.
  • Recognize how users of our software utilize it.
  • Help complete the exception data gathered from other systems.

Flexibility and organization in logging

We can collect structured logs in a variety of formats, including JSON, plain text, and XML, thanks to Serilog’s straightforward and adaptable logging API.
You can utilize the information to create a more optimized version of your application when you and your team have had a chance to analyze the application.

Compatibility with popular .NET frameworks

With built-in connection with well-known ASP.NET Core framework, Entity Framework, and Microsoft.NET Framework are popular .NET frameworks. Extensions, Serilog is most frequently utilized within the .NET community. Logging.

Scalability and Effectiveness

Large amounts of log data can be handled effectively by Serilog. The performance for Serilog is excellent With features such as asynchronous logging and lazy message generation, In addition to batching log messages, it was designed with minimal impact on the application’s performance.

NET community. Logging.

What configuration should be used for Serilog?

In the first example, Serilog is configured to log information to a text file using a file sink, whereas, in the second example, it is configured to log information both to a console and to a text file using the same configuration JSON file.

You can test this example here by cloning My Github Repository

Start the Visual Studio application and start a new project Choose ASP.NET Core Web API Template What is the name of your project? Ensure that the Framework dropdown menu says “.NET 6.0” as well as the additional information page. Ctrl + Create.

Try running the project after it has been created by pressing F5 or Debug. A Swagger API Web page will open in the new browser tab, and you will notice.

Repository

How to set up Serilog dependency

Before putting the code into practice, dependencies must be installed. There are two ways to do this: using the GUI and using the Package Manager Console.

Serilog.AspNetCore

GUI

Your project’s name, Dependencies, Packages, and right-click Manage NuGet Packages in the Solution Explorer Window.

The browse tab opens the NuGet package manager, where you may search for and install Serilog.AspNet.Core as seen in the below image.

Package Manager Console

You can also install dependencies through the Package Manager Console. Simply select Tools NuGet Package Manager Console to accomplish this. The following commands are run to install Serilog requirements. The console is brought up.

  • Install-Package Serilog
  • Install-Package Serilog.Sinks.Console
  • Install-Package Serilog.Sinks.file

Data can be recorded in a text file Using the Verilog file sink

In this first example, I’ll use the Verilog file sink to log the data to a text file.
Open the file program. cs. Modify the code provided below in that file.

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://test.com/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Change: The code in appsettings.json by opening it and doing as shown below.

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "../logs/webapi-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-dd-MM HH:mm:ss.fff zzz} {CorrelatiId} {Level:u4} {User} {Msg:lj}{Exception}{NewLine}"
}
}
]
}
}

Controllers: WeatherForecastController.cs in the Solution Explorer window. Replace the code below.

using Microsoft.AspNetCore.Mvc;

namespace SerilogTutorial.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Liquid = new[]
{
"A$", "B#", "C&", "D*", "E@", "F#", "G%", "H@", "I%", "J#"
};

private readonly ILogger<WeatherForecastController> _logger;

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

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {

        _logger.LogInformation("Seri Log is Working");

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Liquid[Random.Shared.Next(Liquid.Length)]
        })
        .ToArray();
    }
}
}

Run the Project: Try hitting the GetWeatherForecastEndpoint once the SwaggerAPI Page in the browser is opened.

GetWeatherForecast

It adds a log text file and a logs folder to your Project folder. The project log can be found in the log.txt file if you open it.

Conclusion:

Serilog makes structured logging easy to use, set up, and apply in your .net application. It offers a wide range of sinks, making it simple for us to log application information according to your demands. Based on that data, you will comprehend the events, failures, and performance indicators of your application

All product and company names are trademarks™, registered® or copyright© trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Related Blog

ASP.NET Core Web API
How To Implement Serilog In ASP.NET Core Web API

"The SeriLog library is one of the most popular and widely used logging libraries among developers of a Microsoft ASP.NET Read more

Best Dot Net based CMS Platforms
Top .NET-Based CMS Platforms to Elevate Your Business

Does your CMS platform help you keep up your business with your competitors? The reason why you should use the Read more

The Complete Guide to Content Security Policy
The Complete Guide to Content Security Policy (CSP) in ASP.NET

Is there a sure way to safeguard your web application in ASP.NET? What do you do while running your web Read more

Stay in the know with our newsletter
  • Stay in the know with our newsletter

    Subscribe our newsletter and get the latest update or news in your inbox each week