File/Rolling File Logging in ASP.NET Core using SeriLog

SerilLog

Today in this article, we will see how to do file/rolling file logging using Serilog in ASP.NET Core API application.

We shall be leveraging the DI( Dependency Injection) framework to inject the Serilog logger object into the API pipeline.

Today in this article, we will cover below aspects,

Logging in .NET 3.1 onwards framework is simplified further.

In the last article, we saw how to Enable Logging in ASP.NET Core using Built-in Providers.

We also discovered that the File/Rolling File logging provider is still not available through the framework and we need to rely on external solutions like Serilog.

Microsoft recommends using a third-party logger framework like a Serilog or NLog or Log4Net for other high-end logging requirements like Database or File/Rolling File logging.

In this post, we will understand, how to enable file/ rolling file logging in using Serilog and do customization to existing behavior using an example.

Getting started

Create an ASP.NET Core API using .NET Core 3.1 or .NET 6

File Logging in ASPNET Core 5


Please add below NuGet Packages,

Please use the latest available version available for the ASP.NET Core version.

To set the Serilog log as a logging provider for logging purposes, please add below NuGet package,

PM> Install-Package Serilog.AspNetCore -Version 3.2.0

Note: Please use the latest Nuget version available

The above package will help to target Serilog as a logging provider.

Now hereafter depending on the type of provider support adding Serilog will help you log in to that source.

Examples. Console or File logging

Here below we will see how to enable File logging,

For Rolling File logging-

  Install-Package Serilog.Sinks.RollingFile -Version 3.3.0 

For Regular File logging-

Install-Package Serilog.Sinks.File

Or

Please install the above packages through Nuget Package Manager,

File Logging in NET 5

Update Main() method

Please update the Main method for adding the rolling file as shown in the below-highlighted code in the Program.cs

The main method in ASP.NET Core 3.1 and the above framework

Please create logger configuration as below,

//
public static void Main(string[] args)
        {

            Log.Logger = new LoggerConfiguration()
            .WriteTo.RollingFile("Thecodebuzz-log-{Date}.txt")
            .CreateLogger();
            CreateHostBuilder(args).Build().Run();

            Log.CloseAndFlush();
        }

Basic File Logging

For basic file, logging create the logger configuration as below (for both asp.net core 2.2 and 3.1)

 Log.Logger = new LoggerConfiguration()
            .WriteTo.File("Thecodebuzz-log-{Date}.txt")
            .CreateLogger();

Update Host Builder ASP.NET Core API Pipeline

Please update the CreateHostBuilder() method for Serilog as below,

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseSerilog();

Now you are all set to use Serilog in ASP.NET Core!!

Let’s now log in to Controller using the regular ILogger Interface.

Here below controller uses the ILogger interface using dependency injection.

    //
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }
        // GET api/values
        [HttpGet("{id}")]
        public ActionResult<IEnumerable<string>> Get(int id)
        {
            _logger.LogInformation("Start : Getting item details for {ID}", id);

            List<string> list = new List<string>();
            list.Add("A");
            list.Add("B");

            _logger.LogInformation("Completed : Item details for {ID}", list);
            return list;
        }
    }

Once the code is executed the file will be created in the project directory and logging will be captured as shown below figure.

You can enable logging on any controller or any other layer of your API like the Business or domain layer easily. Also as shown above logging can be enabled on Startup.cs and Program.cs files as well.

Below is an example of file logging created by Serilog,

Please note the logging configuration will be used as-is from the default configuration i.e. specified in the apsetting.json.

CreateDefualtBuiilder which helps to create a generic web host builder sets up the default configuration and loads the appsettings.json configuration.

All the logs will be logged based on the Log level severity specified in the apsetting.json file for the logger.

Example :

 "Logging": {
    "LogLevel": {
      "Default": "Warning",
    }
  }

For the above logging configuration, only “Warning” above logs will be logged to a file.

Similarly for the below configuration Information and the above log level will be logged.

 "Logging": {
    "LogLevel": {
      "Default": "Information",
    }
  }

Serilog can also be used to override default configuration easily.

What is a Rolling file?

By configuring the log file as rolling, you get the capability to create a logging file based on dates or file size or name format, and many more custom options. Your file keeps rolling as per provided criteria.

One can use the same concept for .NET Core Console/Desktop Application logging as well.

Other useful references :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

File/Rolling file logging provider is not yet available through the .NET Core framework and certainly, we need to depend on custom or any existing external solutions.

It’s very easy to configure file logging in .NET Core WebAPI using Serilog. Serilog helps us enable logging in a few simple steps and address the file-based logging need easily.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.