It is common for a need to log application errors or including trace log for ease of troubleshooting issues that may arise. By default, the .NET itself already provided a few classes (For example: FileStream, TextWriter, etc) that allows you to write content into file. But what if you want to include logs that are written by the .NET itself, or customize the .NET log content, or write the same content to many different destination (eg: File, ElasticSearch, BlogStorage, etc). Then Serilog can help you with it.
For the prerequisites, it is required to NuGet the following 2 packages
- Serilog.AspNetCore
- Serilog.Sinks.File
Next, head to Program.cs file. You will need to call to the extension method UseSerilog() to start using Serilog.
Method 1: Configure Serilog in code.
loggerConfiguration
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day));
.UseSerilog((hostBuilderContext, loggerConfiguration) =>
loggerConfiguration
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day))
Method 2: Configure Serilog from appSettings file.
"Name": "Console"
{
"Name": "File",
}
]
}
loggerConfiguration
.ReadFrom.Configuration(hostBuilderContext.Configuration));
.UseSerilog((hostBuilderContext, loggerConfiguration) =>
loggerConfiguration
.ReadFrom.Configuration(hostBuilderContext.Configuration))
What the above code snippet does is to write the same log content into console and log file.
Based on the specified path value, the file format will be log{yyyyMMdd}.txt (example: log20220227.txt). And since the configuration mentioned the rolling interval is Day, everyday a new file will be created whenever there are new content to be logged. For more details on what can be further customized for the file, you can head over to https://github.com/serilog/serilog-sinks-file.
You may be wondering what is the difference of the above code snippet compared to creating a new instance of logger with CreateLogger(). First would be to include .NET logs into the file. Second, you will be able to rely on the Microsoft logging library (Microsoft.Extensions.Logging) and inject the instance of ILogger to any of your class through the constructor. Any logs written through the ILogger will be written into your file as well as the console output.
Sample Code: https://1drv.ms/u/s!Aj2AA7hoIWHm1G4BIALQnYew9KFY?e=bIa0tq
No comments:
Post a Comment