Logging Brilliance in .NET Core: Using of Serilog

.NET Core

What is Logging?

Logging in software refers to the process of capturing real-time events along with additional details like infrastructure information and execution time. It plays a crucial role in any software application, particularly when troubleshooting issues. Logs aid in understanding failures, identifying performance bottlenecks, and facilitating problem resolution.

Logs are typically stored in databases, consoles, or files, based on application severity and convenience. While it's possible to record various data in logs, common entries include informational messages and error messages. Informational messages document standard events like method calls, user authentication, or product checkouts, while error messages provide comprehensive data for debugging.

ASP.NET Core simplifies logging by providing a generic logging interface that is consistent across the framework and third-party libraries. This uniformity eases log navigation and problem diagnosis. The framework allows users to configure log verbosity and direct logs to different destinations such as files, consoles, or databases.

In ASP.NET Core, logging providers are responsible for storing logs, and users can configure multiple providers for their applications. The default ASP.NET Core configuration includes logging providers like Console, Debug, EventSource, and EventLog (specific to Windows).

Understanding the Distinction: Logging vs. Monitoring in Software Systems

ASP.NET Core comes with useful features for keeping track of what happens in your applications, known as logging. Logging involves recording detailed information about various events and processes, such as user actions, system events, and performance metrics. This information is typically stored in a log file or database, helping you identify and fix issues, improve performance, and understand how your software is used.

Monitoring, on the other hand, is about watching and measuring your application's performance in real time. It can send alerts or notifications when certain conditions are met, like when the application takes too long to respond or encounters an error. Monitoring helps you catch and fix problems before they impact users, and it provides valuable insights for optimizing performance.

In ASP.NET Core , there are popular tools like Microsoft.Extensions.Logging, NLog, and Serilog that assist with logging. These tools make it easier to manage and analyze the information your application generates, helping you maintain a healthy and efficient software system.

More Details,

In .NET Core, logging is a way to keep track of what's happening in your application. It helps you monitor its behavior, find and fix issues, and understand how it's performing. The ILogger API is used for efficient and structured logging. Different logging providers allow you to store logs in various places, and there are both built-in and third-party options.

Now, let's talk about the difference between logging and tracing. Logging focuses on recording significant events in your application, providing a kind of summary. On the other hand, tracing goes deeper by giving you a more detailed view of everything happening in your application, offering a complete record of its activities. Think of logs as organized records of important moments, while traces give you a comprehensive look at the entire operation of your application.

The six main logging levels in .NET

  1. Critical: This is for really serious issues that could make your app stop working, like running out of memory or space on the disk.
  2. Error: Use this when something goes wrong, like a database error preventing data from being saved. The app can still work for other things despite encountering errors.
  3. Warning: Not as severe as errors, but it indicates a potential problem that might lead to more serious errors. It's a heads-up for administrators.
  4. Information: Gives details about what's happening in the app. Helpful for understanding the steps leading to an error.
  5. Debug: Useful during development for tracking detailed information. It's not typically used in a live/production environment.
  6. Trace: Similar to Debug but may include sensitive info. Rarely used and not utilized by framework libraries.

Implement the External Logging Source to Logging Information of API  and Windows Service - Serilog 

Packages need: Serilog.AspNetCore 

  • Dot Net CLI - dotnet add package Serilog.AspNetCore --version 8.0.0
  • Package Manager - Install-Package Serilog.AspNetCore -Version 8.0.0

Confiuration of Serilog in API

  • Settings File
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "Serilog": {
        "Using": [ "Serilog.Sinks.File" ],
        "MinimumLevel": {
          "Default": "Information",
          "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
          }
        },
        "WriteTo": [
          {
            "Name": "File",
            "Args": {
              "path": "C:/Log001/log_.log",
              "rollOnFileSizeLimit": true,         
              "rollingInterval": "Day"
            }
          }
        ]
      }
    }
    
  • Application Startup updates for Logging
    using Serilog;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    /// Step 1 
    builder.Host.UseSerilog((context, configuration) =>
    { 
        configuration.ReadFrom.Configuration(context.Configuration); 
    }
    );
    
    var app = builder.Build();
    
    
    /// Step 2
    app.UseSerilogRequestLogging();
    
    app.Run();
    
  • Using the setup to Log actions.

    In this setup, we employ the "Assembly - Microsoft.Extensions.Logging.Abstractions, Version=8.0.0.0" for logging actions, and we utilize Serilog to write these logs into files. The ILogger interface is injected into the constructor to facilitate logging functionality.

    private readonly ILogger<WeatherForecastController> _logger;
    
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.LogInformation("Method Entered");
    
        var list = 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();
    
        string message = $"WeatherForecast Count {list.Length}";
        
        _logger.LogInformation(message);
    
        _logger.LogInformation("Method Exit");
        return list;
    }

Now, to test the logging functionality, run the application and inspect the specified path. Refer to the image below for guidance.

All Good,

Certainly, to enhance your API pipeline, you can create custom middleware to capture details about requests, responses, and exceptions. Please refer to the article below for guidance on implementing "Custom Middleware."

Source CodeCode Reference

We will see next article for Worker service Logging


Similar Articles