What Is Serilog In .NET Core?

Hello friends, In this article, we will learn about logs and Serilog in .NET Core and also save logs in text files.

What is logging?

  • Logging is a basic required highlight for identifying and analyzing issues in applications.
  • Logging systems make it simple to log occasion information to Design in Development for log targets.
  • However, if your log file carries unstructured data, it becomes a nightmare to query the data.
  • Organized logging makes it simple to inquire about occasion information by making beyond any doubt that the information to be logged is composed in that arrange which could be an organized arrange.
  • The format to be XML (Extensible Markup Language), JSON (JavaScript Object Notation), or any other structured format that makes parsing the data easy.

What is Serilog?

  • Serilog provides diagnostic logging to files, the console, and in files.
  • It is simple to set up, has a clean API, and is portable between recent .NET platforms.
  • Serilog is a third-party and open-source library that integrates nicely with ASP.NET Core and allows developers to easily log-structured event data to the console, to files, and various kinds of log targets.

Advantages of Serilog

  • Structured logging and enrichment.
  • Great documentation and community.
  • C# based configuration.

Let us understand with the help of an example.

Open VS 2019, we need to click on the Create a new project box.

Now, set the Project Name and Location, and then click on the Next button.

Now, set the Target Framework as .NET 3.1, and then click on the Create button.

Install NuGet packages

We need to install the Serilog, Serilog.AspNetCore, Serilog.Filters.Expressions, Serilog.Settings.Configuration and Serilog.Sinks.Console

Open the appsettings.json and paste the following code into it.

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning' or @Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/SerilogEx.txt",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }    
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  },
  "AllowedHosts": "*"
}

Open the HomeController.cs and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace SerilogDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            _logger.LogInformation("LogInformation log");
            _logger.LogDebug("Log Debug");
            _logger.LogWarning("Log Warning");
            _logger.LogError("Log Error");
            _logger.LogCritical("Log Critical");
            return View();
        }
    }
}

Now you have to run the Index page and one Logs folder will be created in your solution. In your Logs folder, one txt file will be created SerilogEx.txt.

Output

Conclusion

In this article, we have learned about logging and Serilog, and the advantages of serilog with the help of a small demo that shows you the entry of every log in my text file. You can also download the code from my Github repository.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories