Why no entries are appearing in Event Viewer by EventLog provider?

Viewed 116

I have a dotnet core 3.1 Web API published to IIS with unmanaged application pool on a Windows 10 Enterprise x64 machine.

I'm trying to configure EventLog provider like this...

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

...but nothing is appearing in Event Viewer when I do logger.LogInformation("can you see me?");

Here is the appsettings.json, program.cs and Controller

appsettings.json

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

Program.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>();
            });
}

Controller:

  [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";
        }
    }
1 Answers

You need to create the custom event log source Web API ABC on the server where your app is running (one-time setup), before you can write logs to it.

Here is an example using PowerShell to create your event log source:

$ErrorActionPreference = "Stop"

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