有条件地 select log providers with systemd

Conditionally select log providers with systemd

我的 ASP.NET Core 3.1 应用程序仅用于登录到控制台。现在我添加了 systemd 集成。接下来我使用 third-party package to enhance the logging to the journal。问题是,应用程序必须在 systemd 和 Windows 开发控制台中工作。如果我添加这两个提供程序,我会在 Linux/systemd.

中得到重复的日志条目

如果找到 systemd,我如何有条件地 select 日志提供程序?

private static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .UseSystemd()
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                if (__isSystemd__)
                {
                    logging.AddJournal(options =>
                    {
                        options.SyslogIdentifier = "myapp";
                    });
                }
                else
                {
                    logging.AddConsole();
                }
            });
            webBuilder.UseStartup<Startup>();
        });
}

我发现 UseSystemd adds a service 我可以测试。但是我找不到可以告诉我有关已注册服务的信息。

好的,经过大量挖掘,我找到了一个解决方案,然后是一个更好的解决方案。这些去我的问题说 if (__isSystemd__).

#1:

if (logging.Services.Any(s => s.ImplementationType == typeof(SystemdLifetime)))
{
    // add journal logging
}

#2:

if (SystemdHelpers.IsSystemdService())
{
    // add journal logging
}

SystemdHelpers class 来自 Microsoft.Extensions.Hosting.Systemd 包,该包也提供了 UseSystemd。它将其决定缓存在静态变量中,因此它可能是最快的选择。它还使用此信息来确定是否执行所有 systemd 操作(例如注册关心通知的 SystemdLifetime 服务)。