Setup Serilog logging on ASP.NET 5

Last modified: June 13, 2021
Step 1

Create an ASP.NET Core MVC application.

Step 2

We need to install Serilog nuget packages. You can either install them via nuget package manager or simply edit the Serilog_demo.csproj file.

<ItemGroup> <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" /> <PackageReference Include="Serilog.Enrichers.Context" Version="4.2.0" /> <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" /> </ItemGroup>
Step 3

Configure the appsetting.json to adjust the warning level as per your need. In the below configuration, we set the error message level to warning and configure the log output to file (to Logs/log.txt file).

{ "AllowedHosts": "*", "Serilog": { "using": [], "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Warning", "System": "Warning" } }, "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/log.txt" } } ] } }
Step 4

We configure the application to read settings from appsettings.json for configuration. In the main method of the program.cs file, add these commands as following

public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile(("appsettings.json")) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); try { CreateHostBuilder(args).Build().Run(); } catch (Exception ce) { Log.Error(ce.Message); } finally { Log.CloseAndFlush(); } }
Step 5

In the CreateHostBuilder method we need to add .UseSerilog() to it.

Host.CreateDefaultBuilder(args) .UseSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Step 6

Finally, in the start up file, in configure method we add below statement.


To test if the logging works or not, we add the warning message on the home controller and run the application. Exit the application and check for newly created the Logs folder. There is a log.txt file containing the log.

serilog serilog