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
1using Serilog;2using Serilog.Events;3
4...5
6var logger = new LoggerConfiguration()7 .WriteTo.Console()8 .WriteTo.File("logs/log.txt", shared: true)9 .WriteTo.File("debug/debug.txt", shared: true, rollingInterval: RollingInterval.Hour, restrictedToMinimumLevel: LogEventLevel.Debug)10 .WriteTo.File("fatal/fatal.txt", shared: true, rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Fatal)11 .CreateLogger();12
13logger.Information("Hello World!");
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
1{2...3 "Serilog": {4 "WriteTo": [5 {6 "Name": "File",7 "Args": {8 "path": "logs/info/info-.txt",9 "rollingInterval": "Day",10 "shared": true11 }12 },13 {14 "Name": "File",15 "Args": {16 "path": "logs/errors/errors-.txt",17 "rollingInterval": "Day",18 "shared": true,19 "restrictedToMinimumLevel": "Warning"20 }21 }22
23 ]24 },25 ...26 }
This can then be loaded into a logger instance with:
1var config = new ConfigurationBuilder()2 .AddJsonFile("appsettings.json")3 .Build();4
5var logger = new LoggerConfiguration()6 .WriteTo.Console()7 .ReadFrom8 .Configuration(config)9 .CreateLogger();
Logging Service
Lastly, you can also make use of a logger service in Web Application using the Startup.cs/ConfigureServices
function with the following:
1services.AddScoped<Serilog.ILogger>(serviceProvider =>2 new LoggerConfiguration()3 .WriteTo.Console()4 .ReadFrom5 .Configuration(serviceProvider.GetRequiredService<IConfiguration>())6 .CreateLogger()7);
And then use this using Dependency Injecton on a Controller’s Constructor like:
1public MyStuffController(Serilog.ILogger logger)2{3 _logger = logger;4}
And then simply use the logger where required
1public string TestLog()2{3 _logger.Information("Some Log Stuff");4}