Serilog is a popular logging library for .NET applications. It provides a flexible and efficient logging framework that allows developers to log structured data in a variety of formats and sinks (destinations where log data is stored), such as text files, databases, and cloud-based services like Seq.
Serilog stands out for its structured logging capabilities, which allow developers to log data in a structured format (e.g., JSON) rather than plain text. This structured data can then be easily parsed and analyzed by log management systems, making it particularly useful for troubleshooting and monitoring applications in production environments.
Serilog supports a wide range of logging features, including log levels, message templates, contextual logging with property enrichment, and support for custom sinks and enrichers. It's widely used in the .NET ecosystem and is known for its simplicity, flexibility, and performance.
Create a asp.net core project. You can name a project anything but you
can’t named serilog. Because it is a package name and you will get error.
Download package from nuget
dotnet add package Serilog.AspNetCore
Create a folder Services.
Create interface named it IMathService.
Write the following code
public interface IMathService
{
decimal Divide(decimal a, decimal b);
}
Create a class MathService:
public class MathService : IMathService
{
private readonly ILogger<MathService> _logger;
public MathService(ILogger<MathService> logger)
{
_logger = logger;
}
public decimal Divide(decimal a, decimal b)
{
_logger.LogInformation("Parameter 1: " + a);
_logger.LogInformation("Parameter 2: " + b);
decimal result = 0;
try
{
result = a / b;
}
catch (DivideByZeroException ex)
{
_logger.LogWarning(ex, "You cannot divide by zero.");
throw ex;
}
return result;
}
}
In program.cs file add the following code:
builder.Services.AddTransient<IMathService,
MathService>();
////Add support to logging with SERILOG
builder.Host.UseSerilog((context,
configuration) =>
configuration.ReadFrom.Configuration(context.Configuration));
app.UseStaticFiles();
//Add support to logging request with
SERILOG
app.UseSerilogRequestLogging();
Github: https://github.com/itsjubayer/Serilog.git