Logging
Logging and Logging Libraries for .NET
Updated: 03 September 2023
Logging can be done in a bunch of different ways, but the best one I’ve found this far is Serilog
, and the setup is as follows:
Install Serilog
You will need to add the following dependencies to your application from NuGet
Serilog
Serilog.Sinks.Console
Serilog.Sinks.File
Serilog.Settings.Configuration
Basic Logger
Setting up a basic logger that will log to a file or console can be done as follows, using rolling log files and logger instances that can be shared between processes. There are a lot of other config options but these are the main ones
Using Configuration
Additionally you can set the loggers up using the appsettings.json
file as well, for which the Serilog
parts will be as follows
appsettings.json
This can then be loaded into a logger instance with:
Logging Service
Lastly, you can also make use of a logger service in Web Application using the Startup.cs/ConfigureServices
function with the following:
And then use this using Dependency Injecton on a Controller’s Constructor like:
And then simply use the logger where required