You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 Worker Service在Windows Server启动时遇EventLog平台不支持异常求助

解决.NET 6 Worker Service在Windows Server上的EventLog平台不支持错误

核心问题分析

你的代码中同时调用了.UseSystemd()和.UseWindowsService(),这会导致Windows环境下Host初始化时加载了针对Linux的Systemd日志组件,进而引发EventLog访问的平台冲突错误。此外,默认日志配置可能未正确绑定Windows EventLog提供器。

解决方案步骤

  • 移除跨平台服务配置冲突:根据运行平台条件化添加服务适配配置,Windows环境仅启用UseWindowsService,Linux环境才启用UseSystemd。
  • 确保正确引用EventLog日志包:确认项目已安装Microsoft.Extensions.Logging.EventLog 6.0.0版本,避免版本不匹配。
  • 显式配置EventLog日志提供器:手动指定日志配置,确保Windows环境下优先使用EventLog。

修改后的代码示例

static async Task RunService()
{
    try
    {
        var hostBuilder = Host.CreateDefaultBuilder()
            .ConfigureServices(services =>
            {
                services.AddHostedService<Worker>();
            })
            .ConfigureLogging(logging =>
            {
                // 仅在Windows环境添加EventLog日志提供器
                if (OperatingSystem.IsWindows())
                {
                    logging.AddEventLog(config =>
                    {
                        config.LogName = "Application";
                        config.SourceName = "YourWorkerServiceName";
                    });
                }
            });

        // 根据平台添加对应的服务适配
        if (OperatingSystem.IsWindows())
        {
            hostBuilder.UseWindowsService();
        }
        else
        {
            hostBuilder.UseSystemd();
        }

        var host = hostBuilder.Build();
        await host.RunAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

额外检查项

  • 确认Windows Server上的EventLog服务已正常运行,且运行Worker Service的账户具有读取/写入EventLog的权限。
  • 清理项目的obj和bin目录,重新构建发布,避免旧的依赖缓存导致的问题。

内容的提问来源于stack exchange,提问作者zynovij

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:50:27