Logging with Serilog in .NET

A logger might be one of the most boring task to do while coding, but fortunately there is packages like Serilog that handles that for you. I don’t have that high demands for a logger, as long as it outputs my log entries where I want it and the way I want while beeing easy to use, I’m happy 🙂

Installing Serilog

The first thing you’ll need to do is add Serilog to your project with nuget.

Apart from that you will also need sinks which is not in the core package. The easiset way to find those are probably to search for Serilog in nuget package manager. The first one I will use is Serilog.Sinks.ColoredConsole.

Setup Serilog

To create a global ColoredConsole logge, this is all you need to do:

And of course, if you want a local logger:

And to actually output anything you can try this:

If you try to run this you will only see 4 of the 6 prints (Information, Warning, Error and Fatal) and this is because you have a minimum level set. The default minimum level is Information, which means that everything including and above Information will be displayed.

Output with serilog

If you want to see verbose and debug as well you need to change the minimum level, This is done when initializing the logger:

And this is the result

Output with serilog

I want more!

Usually it’s pretty useful to log the same logs to different sinks, at least one to console and one to file. And this is also pretty straight forward during initialization:

There are a log more features for serilog like

  • Sinks – Write to more places such as mail, azure, rabbitmq and more
  • Enrichers – Enrich your logs with different properties sucha as thread id
  • Filters – filter out specific entries

Conclusion

There is a lot more to do with Serilog than I have described here and if you are interested you should go to the documentation and check out what you really can do. From my perspective it does everything i want a logger to do which is log to console, file, rolling file and being able to set levels for each while at the same time being lightweight and easy to add.

 

Leave a Reply

Your email address will not be published. Required fields are marked *