Implementing Logging in a .NET Core Web Application using Serilog

Setting up default logging

Create a new MVC application from Visual Studio. By default, Logging is enabled in the application via the ILogger interface. It has got some built-in providers for writing the log information to the console, event log as well as for third-party providers such as NLog, Serilog, etc.

For example, if you want to write logging information to the console window or event log, you will need to configure it in the CreateDefaultHostBuilder method in the Program.cs file as shown below.

 public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.AddConsole();
        logging.AddEventLog();
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup();
    });

In the case of a web app, you will get an ILogger from the DI container and use that object for writing into the configured log providers. Let's see how we can do that in the HomeController

First, create a private variable for the logger interface.

private readonly ILogger<HomeController> _logger;

Then modify the constructor as shown below

public HomeController(ILogger logger)
{
    _logger = logger;
}

Now, use the LogInformation method available in the logger interface to write a message into the log

public IActionResult Index()
{
    _logger.LogInformation("Writing to log");
    return View();
}

If we run the application and goto the home page now, you will see this message written to the console.

To write an error, we normally use LogError method as shown below

public IActionResult Index()
{
    _logger.LogInformation("Writing to log");
    _logger.LogError("Error from Serlog sample");
    return View();
}

And the output will be

Implementing Serilog to log in a flat-file

First, you will need to install the necessary packages given below.

Install-Package Serilog
Install-Package Serilog.Extensions.Logging
Install-Package Serilog.Sinks.File

Modify the appsettings.json file to include the path for the log file

"Logging": {
    "LogPath": "logs//ex.log",
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

Then modify the Program.cs file to read these values from the JSON file

var configSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

.ConfigureAppConfiguration(config =>
{
    config.AddConfiguration(configSettings);
})

Now, to hook up Serilog provider, import the namespace first and then modify CreateHostBuilder method to set up the logger

using Serilog

Log.Logger = new LoggerConfiguration()

    .WriteTo.File(configSettings["Logging:LogPath"])
    .CreateLogger();

.ConfigureLogging(logging =>
{
    logging.AddSerilog();
})

Here's the method is full

public static IHostBuilder CreateHostBuilder(string[] args)
{
    var configSettings = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()

        .WriteTo.File(configSettings["Logging:LogPath"])
        .CreateLogger();

    return Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(config =>
    {
        config.AddConfiguration(configSettings);
    })
    .ConfigureLogging(logging =>
    {
        logging.AddSerilog();
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup();
    });

}

Now if we run the application, you will see the information being written to the file mentioned in the path.


No Comments

Add a Comment

Recent Posts