Serilog EventLog Sink is not Logging
Asked Answered
K

1

6

I've installed the Serilog.Sinks.EventLog sink into a little Background Worker Service project. However, none of the logs which I am attempting to write are showing up in the Event Log.

This is the body of my Main method. The RecurringTasks.Service which is specified as the source has already been created (by me manually).

Log.Logger = new LoggerConfiguration()
    .WriteTo.EventLog(source: "RecurringTasks.Service", logName: "Application")
    .CreateLogger();

Log.Logger.Information("Test message");

try
{
    var host = CreateHostBuilder(Log.Logger, args).Build();
    host.Run();
}
catch (Exception e)
{
    Log.Fatal(e, "Host terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

Any ideas as to why the "test" message was not written to the EventLog? Cheers

Kamkama answered 27/8, 2021 at 2:59 Comment(0)
M
9

The first rule of Serilog troubleshooting is to enable SelfLog and see what error messages are being thrown by the Serilog sink.

Most likely the source RecurringTasks.Service doesn't exist on the machine and needs to be created first before you can write to it.

If your application is running using an account with admin rights (or the account has explicit permission to create event log sources) you can tell Serilog to create the source for you by setting manageEventSource to true:

Log.Logger = new LoggerConfiguration()
    .WriteTo.EventLog(source: "RecurringTasks.Service",
                      logName: "Application",
                      manageEventSource: true) // <<<<<<<
    .CreateLogger();

Otherwise you can create the event log source manually (one-time setup per machine). Open a command-prompt as administrator and run:

eventcreate.exe /ID 1 /L APPLICATION /T INFORMATION  /SO "RecurringTasks.Service" /D "RecurringTasks.Service"

Other alternatives using PowerShell or Registry: Question: Create Event Log manually #31

--

N.B.: An easy hack you can use is to write your logs to a source called Application which is guaranteed to exist in the machine, as it's where all the common Windows logs go. That way you don't have to create a new source (and don't need special permissions to write). e.g.:

Log.Logger = new LoggerConfiguration()
    .WriteTo.EventLog(source: "Application")
    .CreateLogger();

Related:

Memling answered 27/8, 2021 at 3:37 Comment(1)
I'll mark this as the answer, but it just started working for no discernible reason.Kamkama

© 2022 - 2025 — McMap. All rights reserved.