Serilog
Logging in Serilog is dead simple:
Log.Information("Hello World");
Remember how we initialized the Log class in a previous section? Well, here we really see the benefit. The Log class has overloads for all available log levels through Serilog. In this example, I log an information message.
A great benefit of Serilog is the feature of structured logging:
Log.Information("Hello World from {FirstName}", "Thomas");
Rather than using normal string concatenation, I tell Serilog to replace {FirstName} with Thomas. This produces a nice log message, as well as tells Serilog to remember the FirstName
key and its value. This can be used to log structured data in a service
like elmah.io or in NoSQL databases like MongoDB or Elasticsearch.
This isn't a guide to structured logging with Serilog. If you don't know the concept, check out
Structured Data on the Serilog wiki. You are in for a treat!
log4net
Logging through log4net is a bit more complex than Serilog, but it still does the job:
var log = LogManager.GetLogger(typeof(Bar));
log.Info("Hello World");
The main difference is the need for the LogManager. You typically get a reference to the logger one time per class and re-use the same log instance.
log4net doesn't support the concept of structured logging. Like shown in the conversionPattern element in the XML configuration, you have some variables to play with when writing to the storage. But including properties like FirstName in the Serilog example isn't available.
Serilog and log4net are popular choices when choosing a logging framework in .NET. Read this guide to learn all about each framework and what to pick.
blog.elmah.io