Advanced Serilog Logging Methods in ASP.NET Core 8

Leave a Comment

Applications must be logged in order to monitor and analyze any problems or errors that may arise during development. Serilog is a well-liked and generally helpful tool for developers to log; it offers organized logging that makes it easier for developers to locate problems and errors fast.

A diagnostic logging library for.NET applications is called Serilog. It offers a straightforward, adaptable, and effective method for logging errors, application events, and other data. Because Serilog is built for structured logging, it can log more than just text messages; it can log rich, structured data.

Key Features of Serilog

  • Structured Logging: Serilog allows you to log structured data, which makes it easier to query and analyze logs. For example, you can log an object with multiple properties, and each property can be indexed and queried separately.
  • Sinks: Serilog supports various “sinks” that allow you to write logs to different storage systems, such as files, databases, consoles, and cloud services like Azure Application Insights, Elasticsearch, and more.
  • Configurable: Serilog is highly configurable. You can configure it to write logs to multiple sinks, filter logs by severity level, enrich logs with additional data, and more.
  • Performance: Serilog is designed to be performant and to minimize the impact on your application’s performance.
  • Integration: Serilog integrates well with other .NET libraries and frameworks, including ASP.NET Core, Entity Framework, and more.

In this article, we will learn how we can use Serilog for logging.

Now, let’s go.

To follow Serilog implementation steps, you can use an existing project where you need to implement logging using Serilog or Create a new Asp.NET Core Web application. Now, let’s go for implementation. For this demo, I am using the ASP.NET Core Web API project.

Step 1. Install the following packages in your project.

  • Serilog
  • Serilog.AspNetCore
  • Serilog.Sinks.File

After the installation of the necessary packages, we will need to configure Serilog in the appsetting.json file. So, in the appsetting.json file, we will add the code below for the Serilog configuration.

"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.log",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true
        }
      }
    ]
  },

Step 2. In the Program.cs we will add the Serilog configuration:

builder.Host.UseSerilog((context, configuration) =>
    configuration.ReadFrom.Configuration(context.Configuration));

Step 3. Then, above the App.Run() write Serilog middleware

app.UseSerilogRequestLogging();

Step 4. Then, we can now log in to any C# class.

Below is an example of logging in WeatherForecastController.

private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}
  [HttpGet(Name = "GetWeatherForecast")]
  public IEnumerable<WeatherForecast> Get()
  {
      _logger.LogInformation("Get Weather forecast called sucessfully");

      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();
  }

Now, let’s run the app and check. When you run the app and call the GetWeatherForecast endpoint of your Api, the log will be captured inside the log folder, and you can open the folder and see the log, which will look like the below one.

Conclusion

An extensive introduction to Serilog, a potent logging package for.NET applications, has been given in this post. We went through its benefits, such as structured logging, and showed you how to use it in an ASP.NET Core 8 application. Developers can get more comprehensive and helpful log data by integrating Serilog, which enhances system maintenance, monitoring, and troubleshooting.

Serilog's structured logging feature improves log analysis and visualization, making it a vital tool for contemporary applications. Observability, dependability, and general health of your application can all be much improved by implementing Serilog.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment