Updated Step by step: Serilog with ASP.NET Core
·276 words·2 mins
Many of you come to my site to read the post Step by step: Serilog with ASP.NET Core which I wrote in 2016 and is completely out of date, so with this post I will show you how to setup Serilog to work with your ASP.NET Core 2.2 applications.
Create an ASP.NET Core project # md aspnet.serilog.sample cd aspnet.serilog.sample dotnet new mvc Add the following dependencies to your project # dotnet add package Serilog.AspNetCore dotnet add package Serilog.Extensions.Logging dotnet add package Serilog.Sinks.ColoredConsole Change your Program.cs file to look like the following # using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Core; using Serilog.Events; namespace aspnet.serilog.sample { public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.ColoredConsole( LogEventLevel.Verbose, "{NewLine}{Timestamp:HH:mm:ss} [{Level}] ({CorrelationToken}) {Message}{NewLine}{Exception}") .CreateLogger(); try { CreateWebHostBuilder(args).Build().Run(); } finally { Log.CloseAndFlush(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseSerilog() .UseStartup<Startup>(); } } Inject the logger to your services or controllers # Change the home controller and log some actions: