首页 > 解决方案 > 为什么 EventLog 提供程序在事件查看器中没有出现任何条目?

问题描述

我在 Windows 10 Enterprise x64 机器上使用非托管应用程序池将 dotnet core 3.1 Web API 发布到 IIS。

我正在尝试像这样配置 EventLog 提供程序...

.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddEventLog(new EventLogSettings { LogName = "Web API ABC" 
}

...但是当我这样做时,事件查看器中没有出现任何内容logger.LogInformation("can you see me?");

这是appsettings.json,program.csController

应用设置.json

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

程序.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
             .ConfigureLogging(logging =>
             {
                 logging.ClearProviders();
                 logging.AddConsole();
                 logging.AddEventLog(new Microsoft.Extensions.Logging.EventLog.EventLogSettings { LogName = "Web API ABC" });
             })
                .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

控制器:

  [ApiController]
  [Route("[controller]")]
  public class MyGreatController : ControllerBase
  {
        private IConfiguration config;
        private readonly ILogger<MyGreatController> logger;

        public MyGreatController(IConfiguration _config, ILogger<MyGreatController> _logger)
        {
            config = _config;
            logger = _logger;
        }

        [HttpGet]
        [Route("hello")]
        public string HelloWorld()
        {
            logger.LogInformation("can you see me?");
            return "hello world";
        }
    }

标签: asp.net-coreiisloggingasp.net-core-webapi

解决方案


您需要在Web API ABC运行应用程序的服务器上创建自定义事件日志源(一次性设置),然后才能将日志写入其中。

以下是使用 PowerShell 创建事件日志源的示例:

$ErrorActionPreference = "Stop"

$sourceExists = [System.Diagnostics.Eventlog]::SourceExists("Web API ABC")
if ($sourceExists -eq $false){
    [System.Diagnostics.EventLog]::CreateEventSource("Web API ABC", "Application")
}

推荐阅读