I am using generic host pattern in my project. I need a logger to file specially a rolling file like Serilog. How can I add it to certain logger configuration to the host builder.
In generic host we can add log configuration such as debugger and console. But I want to use a logger to file with specific options. I don't know how to do so.
Which way is the best practice for?
Installing Serilog is simple. First, we open the NuGet Package Manager and search for the Serilog. AspNetCore package and install the latest stable version. After a few seconds, Serilog is installed.
Create a Console Application project in Visual Studio. Install Serilog and its dependencies. Create and configure the Serilog global logger. Integrate the logger into the C# Console Application.
Serilog SinksIn the packages that we are going to install to our ASP.NET Core application, Sinks for Console and File are included out of the box. That means we can write logs to Console and File System without adding any extra packages. Serilog supports various other destinations like MSSQL,SQLite, SEQ and more.
Now that you've configured Serilog in your application, you can take advantage of the built-in interface ILogger to log data in action methods of your controller as shown below. By default Serilog will log events of Information severity level and above.
Thanks to both answers, I need to use both Serilog.Extensions.Hosting
and Serilog.Sinks.RollingFile
. Then it needs to create a logger object so it can be added to host builder, As shown below :
var logger = new LoggerConfiguration().WriteTo.RollingFile(
outputTemplate: outputTemplate,
restrictedToMinimumLevel: LogEventLevel.Information,
pathFormat: Path.Combine(loggingDirectory, "systemlog-{Date}.text")
.CreateLogger();
Note that pathFormat
argument are useful and important.It consists of path and format which is described adequately in Serilog.Sinks.RollingFile( Filename format specifiers). Here i use {Date} format after path which means : It creates a file per day. Filenames
use the yyyyMMdd format.
After creating logger with such a config it needs to be added into HostBuilder
like this:
var host = new HostBuilder()
.ConfigureLogging((context, builder) =>
{
builder.AddConsole();
builder.AddSerilog(logger);
//....<- some other option here
})
.Build();
You'll need Serilog.Extensions.Hosting.
public static IHost BuildHost(string[] args) =>
new HostBuilder()
.UseSerilog() // <- Add this line
.Build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With