Great logs need to be built-in from the first day of a project. It's only by using your application logs during development and testing that they will deliver their full value in production.
In apps based on ASP.NET, a quick way to get started with minimal effort is the little-known SerilogWeb.Classic package.
SerilogWeb.Classic is a NuGet package that adds flexible web request and exception logging to ASP.NET 4.6 apps. (This is the production MVC and WebAPI in use today, based on System.Web – not the OWIN or vNext flavors, hence the "classic" part of the name.)
To get up and running, just install the package:
Install-Package SerilogWeb.Classic -DependencyVersion Highest
With this complete, requests will be timed and logged, along with their status code and associated error if an unhandled exception occurred.
To actually view the events, you’ll need to configure Serilog to send them somewhere. Sinks exist for every imaginable logging target - log files, databases and so-on. A fairly comprehensive list is on the Serilog project site.
We'll use the sink for Seq in this example.
Here’s the code for configuring the logger, which you can add to
Log.Logger = new LoggerConfiguration() .Enrich.With<HttpRequestIdEnricher>() .WriteTo.Seq("http://localhost:5341") .CreateLogger();
The package provides some other neat features like HTTP Request Correlation, enabled by adding
HttpRequestIdEnricher to the logging pipeline.
Requests are logged at the
Information level, while errors are logged as
If you use ASP.NET WebAPI, you'll need to install one additional package before errors are collected.
This installs an implementation of WebAPI's
ExceptionLogger that will capture and record errors consistently.
And that's it! Now there's no excuse not to have great ASP.NET diagnostics right from day "1" of your next project :-)