如何在 C# 中将 serilog 记录器添加到 GenericHost 项目

How to add a serilog logger to a GenericHost Project in C#

我在我的项目中使用通用主机模式。我需要一个记录器来专门归档像 Serilog 这样的滚动文件。如何将它添加到主机构建器的某些记录器配置中。

在通用主机中我们可以添加调试器和控制台等日志配置。但我想使用记录器来记录特定选项。我不知道该怎么做。

哪种方式最适合?

你需要 Serilog.Extensions.Hosting.

public static IHost BuildHost(string[] args) =>
    new HostBuilder()
        .UseSerilog() // <- Add this line
        .Build();

感谢这两个答案,我需要同时使用 Serilog.Extensions.HostingSerilog.Sinks.RollingFile。然后它需要创建一个记录器对象,以便可以将其添加到主机构建器中,如下所示:

var logger = new LoggerConfiguration().WriteTo.RollingFile(
                outputTemplate: outputTemplate,
                restrictedToMinimumLevel: LogEventLevel.Information,
                pathFormat: Path.Combine(loggingDirectory, "systemlog-{Date}.text")
            .CreateLogger();

请注意,pathFormat 参数很有用,important.It 由路径和格式组成,在 Serilog.Sinks.RollingFile(文件名格式说明符)中有充分描述。这里我在路径后使用 {Date} 格式,这意味着:它每天创建一个文件。 Filenames 使用 yyyyMMdd 格式。

使用这样的配置创建记录器后,需要像这样将其添加到 HostBuilder 中:

var host = new HostBuilder()
            .ConfigureLogging((context, builder) =>
            {
                builder.AddConsole();
                builder.AddSerilog(logger);
                //....<- some other option here
            })
            .Build();