最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - .NET 8 Windows service not able to write to event log - Stack Overflow

programmeradmin1浏览0评论

I have a Windows service built with .NET 8 and the BackgroundService class.

When I run the service from terminal, it successfully writes to both the windows event log and the console but when I start it as a service, nothing is logged at all, even though the service is running and operating correctly.

I am aware of the default filter that prevents informational messages from being logged, the messages are using error and critical specifically for testing. The code to setup the service is below.

What am I missing that is preventing the event log from working when it runs as a service?

public class Program {
    public static void Main(string[] args) {
        HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
        builder.Services.AddWindowsService(options => options.ServiceName = "My Test Service");

        builder.Services.AddHostedService<Worker>();

        IHost host = builder.Build();
        host.Run();
    }
}
public class Worker : BackgroundService {
    private readonly ILogger<Worker> _logger;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        _logger.LogError("Starting up");
        _logger.LogCritical("test");
    }
}

I have a Windows service built with .NET 8 and the BackgroundService class.

When I run the service from terminal, it successfully writes to both the windows event log and the console but when I start it as a service, nothing is logged at all, even though the service is running and operating correctly.

I am aware of the default filter that prevents informational messages from being logged, the messages are using error and critical specifically for testing. The code to setup the service is below.

What am I missing that is preventing the event log from working when it runs as a service?

public class Program {
    public static void Main(string[] args) {
        HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
        builder.Services.AddWindowsService(options => options.ServiceName = "My Test Service");

        builder.Services.AddHostedService<Worker>();

        IHost host = builder.Build();
        host.Run();
    }
}
public class Worker : BackgroundService {
    private readonly ILogger<Worker> _logger;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        _logger.LogError("Starting up");
        _logger.LogCritical("test");
    }
}
Share Improve this question edited Mar 17 at 9:06 Tiny Wang 16.5k2 gold badges18 silver badges38 bronze badges asked Mar 14 at 21:26 user29976520user29976520 132 bronze badges 3
  • Windows services run "...in the security context of a specific user account that is different from the logged-on user." The account will need some of the privileges you presumably have when executing "the service from terminal" – ScottWelker Commented Mar 14 at 22:25
  • @ScottWelker the service is running as SYSTEM which should have the ability to event log no? – user29976520 Commented Mar 14 at 22:33
  • We have a document for windows service which also mentioned the log view. Since you mentioned that the service could work well, I trust you've set EventLog configuration in appsettings correctly. But I hope you could double check it. If everything is correct, then I'm afraid this is due to some restriction on your server, maybe a restart could help to apply the role or permission for the service. – Tiny Wang Commented Mar 17 at 9:05
Add a comment  | 

1 Answer 1

Reset to default 1

I can't reproduce your issue, since you didn't share all your codes and configurations, so that I think we could check whether we missed anything in codes ahead, then check other possible issues. You can see what I did below, especially the differences if we have.

I had a test using your codes with a new project created by Worker Service template from VS 2022 following the tutorial.

In my Program.cs, I have codes below:

using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.EventLog;
using WorkerService1;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options => options.ServiceName = "My Test Service");

LoggerProviderOptions.RegisterProviderOptions<
    EventLogSettings, EventLogLoggerProvider>(builder.Services);

builder.Services.AddHostedService<Worker>();

var host = builder.Build();
host.Run();

And here's my appsettings and nuget package version.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "SourceName": "My Test Service",
      "LogName": "Application",
      "LogLevel": {
        "Microsoft": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  }
}

<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>dotnet-WorkerService1-9c5e77dc-ebca-4efe-ac11-4555af860b2d</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.1" />
  </ItemGroup>
</Project>

And I published the app with configurations like below.

Double clicking the exe file could write logs to Event View. Publishing the Service via Powershell command sc.exe create "My Test Service" binpath= "C:\Publish\workService\WorkerService1.exe" and start the service via sc.exe start "My Test Service" could also write the log.

发布评论

评论列表(0)

  1. 暂无评论