Serilog is the most used and widely taken framework for asp.net application. Serilog is basically a logging framework for asp.net application. In this blog I try to dive deep into the implementation of logging with Serilog.
Step 1: Create ASP.NET Core Web API project in Visual Studio. In my case I am using VS 19 and .net framework 5.
Step 2 : Go to Controllers –> WeatherForecastController.cs and simply add this line at the beginning of IEnumerable<WeatherForecast> Get() method
_logger.LogInformation("HTTP GET: Called get method of WeatherForecast contorller");
Now Run the Application but not in IIS Expresses . Select your Project name from the dropdown and hit the Run button. A console window will open with a swagger ui in browser.
Step 3: Expand the WeatherForecast API and click Try it out and Execute button. Now you can see a new line added on the console.
Now Add a custom API Empty Controller named MathController.cs and check the log in console.
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SerilogDemo.Controllers { [Route("[controller]")] [ApiController] public class MathController : ControllerBase { private readonly ILogger<MathController> _logger; public MathController(ILogger<MathController> logger) { _logger = logger; } [HttpGet] public decimal Divide(decimal a, decimal b) { try { return (a / b); } catch (Exception ex) { _logger.LogInformation("Error in Divide Method - Value of a is {a}", a); _logger.LogInformation("Error in Divide Method - Value of b is {b}", b); _logger.LogError(ex, "Error in Divide Method"); return 0; } } } }
Now run the application like previous and execute the /Math API a = 5 and b = 0 . A fail status log will be updated on the console.
The output will like this:
Now INSTALL this NuGet Packages in your solution.
-
Serilog.AspNetCore
-
Serilog.Settings.Configuration
-
Serilog.Sinks.File
-
Serilog.Sinks.Console
Step 1 : Go to appsettings.json . Change the file with this following code.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Serilog": { "MinimumLevel": "Information", "Override": { "Microsoft.AspNetCore": "Warning" }, "WriteTo": [ { "Name": "Console" }, { "Name": "File", "Args": { "path": "Serilogs\\AppLogs.log" } }, { "Name": "File", "Args": { "path": "Serilogs\\AppJSONLogs.log", "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog" } } ] } }
Step 2 : Go to Startup.cs file and add this line in Startup(IConfiguration configuration) method
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Step 3 : Go to Program.cs file and change CreateHostBuilder method
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Run the application and execute execute the /Math API putting a = 5 and b = 0 .
Output:
- A folder named Serilogs will generated and inside this folder two file named AppJSONLogs.log and AppLogs.log will generated.
Open those file.
In this AppLogs.log file you can see the log
And this AppJSONLogs.log file you can see the file log in json format which is described in the last portion of appsettings.json file.
And here is the console output. That’s it. Hope you can dive deeper into the Serilog implementation from this blog. You can also keep log of some more additional information like Machine Name, Assembly Name, HTTP Request Path, etc. which is available with Serilog Enrichers. Hope I will describe this in my another blog.
Give me a star on Github and Download the Project