ASP.NET Core logging with Serilog

Logging is a vital component in a well written application. Correctly implemented it makes debugging easier and functions as an audit log.

I have been using NLog for years. It works fine with ASP.NET Core, but there have been things that annoy me. For instance the inability to hook up to events, requiring writing of custom target modules and messing around with config to make them work. Sure it works, but it is complexity and effort spent where I don’t feel it is necessary.

So recently I have been testing Serilog.

Install

In Packet Manager Console, or NuGet browser, install:

Implement

In Program.cs we want to wrap the full execution of our application, so that we catch any errors during startup. So we read appsettings.json in Program.cs, and we encapsulate the whole execution in a try-catch.

In Program.cs, add using:

Currently your Program.cs should look like this:

Change to:

Note the change of return type from void to int in main. Returning a return code is strictly not necessary, but good practice.

Add configuration section

Add a Serilog section to appsettings.json:

Note that we are setting log level for Microsoft to Error, so we avoid logs filling up with irrelevant .Net Core internal log elements.

Testing

Run application and it will log to Debug (Output-window in Visual Studio) and Logs-folder under project root.

Using

You can go for straight forward use of static Log-object.

Or using Dependency Injection by ASP.NET Core logging interface:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading