简体   繁体   中英

How to setup event log for .NET Core 3.0 Worker Service

I'm working with the new Worker Service app template with .NET Core 3.0 Preview and am trying to add event logging using the AddEventLog method. However, I cannot see any of my logs via the Event Viewer in Windows.

I have a very simple Worker app setup and have configured logging in the Program.cs file as follows:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureLogging((context, logging) =>
    {
        logging.AddEventLog(new EventLogSettings()
        {
            SourceName = "MyTestSource",
            LogName = "MyTestLog"
        });
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddHostedService<Worker>();
    });

I then have some logging statements in the Worker.cs file as follows:

private readonly ILogger<Worker> _logger;

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

public override async Task StartAsync(CancellationToken cancellationToken)
{
    _logger.LogInformation($"Worker started at: {DateTime.Now}");
    await base.StartAsync(cancellationToken);
}

public override async Task StopAsync(CancellationToken cancellationToken)
{
    _logger.LogInformation($"Worker stopped at: {DateTime.Now}");
    await base.StopAsync(cancellationToken);
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        _logger.LogInformation( $"Worker running at: {DateTime.Now}");
        await Task.Delay(1000, stoppingToken);
    }
}

To setup the event logs, I ran the following from an elevated Powershell prompt:

New-EventLog -LogName MyTestLog -Source MyTestSource

If I open the Event Viewer I can see "MyTestLog" listed below "Applications and Services Logs".

Then, to set up my Worker as a Windows service, I ran the following commands from an elevated command prompt:

dotnet publish -o publish (Publishes project and outputs to publish directory)

sc create MyTestService binPath=<path to exe in publish directory>

The service is created successfully, and I can see it in the Services viewer application. From there, I manually start the service and then check back in the Event Viewer and no logs are displayed.

I was expecting there to be some logs. However, the "MyTestLog" section remains empty in the Event Viewer.

So I was able to find the issue reported here .

Essentially it boils down to a change in the latest .NET Core 3.0 Preview where Event Logs are filtered at the warning level by default now. Thus, you cannot see any information logs.

The fix was to simply edit the appsettings.json file to look like the following:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  }
}

This overrides the default set and allows information logs to be viewed again.

I'm using .NET Core 3.1 and Microsoft.Extensions.Logging 5.0.0.

What's posted here got me close but didn't totally solve my problem. The logs were still listed under the "Application" Log Name even through I was resetting it via the ConfigureLogging method.

In order to fix this I had to clear out the providers. This seems like a defect to me with Microsoft.Extensions.Logging.

The solution below does NOT require running the powershell script mentioned in the OP (New-EventLog -LogName MyTestLog -Source MyTestSource)

Working solution for me, nothing else required...

Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.AddConsole();
    
        logging.AddEventLog(new EventLogSettings()
        {
            LogName = "TSEServiceLog",
            SourceName = "TestSavvyExecuteService"
        });
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddHostedService<Worker>();
    })
    .UseWindowsService();

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  }
}

嗨,我在我的 .net 6.0 中使用了这个偶数记录器方法我可以在事件查看器中看到事件日志,但是事件 Id =0 为什么它没有增加,我可以像事件 id++ 一样增加事件 ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM