0

在 .NET Framework 中,我习惯于让我的 Windows 服务写入自定义事件日志,如下所示:

string source = "My Source"
string log = "My Log"
EventLog eventLog;
eventLog = new EventLog(log, Environment.MachineName, source);
eventLog.WriteEntry("The service started.", EventLogEntryType.Information, 1);

当我在“事件日志”的“常规”选项卡上查看事件时,它准确地显示了我写的内容,没有任何额外内容:

The service started.

现在我将此程序作为 ServiceWorker(带有 Windows 服务)移植到 .NET 6,并将日志和源名称存储在 appsettings.json 的相关部分中:

"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "LogName": "My Log",
      "SourceName": "My Source",
      "LogLevel": {
        "Default": "Information"
      }
    }

我在 Program.cs 中配置事件日志,如下所示:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)                
                .UseWindowsService()
                .ConfigureServices((hostContext, services) =>
                {
                    EventLogSettings eventLogSettings = hostContext.Configuration.GetSection("Logging:EventLog").Get<EventLogSettings>();                    
                    services.Configure<EventLogSettings>(settings =>
                    {
                        settings.SourceName = eventLogSettings.SourceName;
                        settings.LogName = eventLogSettings.LogName;                           
                    });
                    services.AddHostedService<MyServiceWorker>();
                });

我的服务工作者的构造函数如下所示:

private readonly ILogger<MyServiceWorker> _logger;

public MyServiceWorker(ILogger<MyServiceWorker> logger)
{
    _logger = logger;
}

我这样写事件日志:

_logger.LogInformation(1, "The service started.");

现在,当我在“事件日志”中的“常规”选项卡上查看该事件时,它显示了两个我不想要的额外标题行(和一个额外的换行符):

Category: MyServiceWorker
EventId: 1

The service started.

我可以防止这种情况吗?如果是这样,此设置在哪里/如何控制?如果不是,为什么不呢?

4

0 回答 0