Header Ads Widget

Implement Serilog Logging in dot net core

To use serilog package in dot net core is quit simple. Please do following steps, just add some line in code and your log can be saved in local file system 

1. Install the Serilog.AspNetCore package

To install package either use nuget package manager by right click on dependencies or

use package manager console

if you are using package manager console type : Install-Package Serilog.AspNetCore

2. Configure serilog by adding these parameter in appsetting.js file


  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Error",
        "System": "Debug"
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
        "Name": "File",
        "Args": {
          "path": "E:\\Serilog\\SerilogRestApiLog.log", // this is the path to save log file you can change this path as per your requirement 
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 4194304,
          "retainedFileCountLimit": 15,
          "rollingInterval": "Minute"

  "AllowedHosts": "*"



3. Add these line of code in program.cs file


           var logger = new LoggerConfiguration()


if you use dot net core  6 or later version then add this on startup.cs file


            var logger = new LoggerConfiguration()


4. Now in controller just call the logger.LogDebug and write a log message 


using Microsoft.AspNetCore.Mvc;
namespace SerilogImplement.Controllers
    public class WeatherForecastController : ControllerBase
        private static readonly string[] Summaries = new[]
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
            _logger = logger;

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
            _logger.LogDebug("Weather forecasr calling");
            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)]


As per this code log file is saved into E:\\Serilog\\SerilogRestApiLog.log",

Post a Comment