Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write logs to EventLog by ILogger<T> in Asp.net Core?

I follow this document Logging in .NET Core and ASP.NET Core, try to write log to Windows EventLog.

first, I create Source and Log in Windows Event Log:

if (!EventLog.SourceExists("MyTestSource"))
{
    EventLog.CreateEventSource("MyTestSource", "MyTestLog");
    return;
}

and it's created.

then, I configured logging in CreateHostBuilder from Program.cs of my ASP.NET Core app (core 3.0):

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddEventLog(new EventLogSettings
            {
                SourceName = "MyTestSource",
                LogName = "MyTestLog"
            });
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

I think that's all. Then I use logger in my controller:

[Route("[controller]")]
[ApiController]
public class ServerController : ControllerBase
{
    ILogger<ServerController> _logger = null;
    public ServerController(ILogger<ServerController> logger)
    {
        _logger = logger;
    }

    [HttpGet("GetServerInfo")]
    public string GetServerInfo()
    {
        _logger.LogInformation("GetServerInfo Called");
        return "Hello I'm Server";
    }
}

but there's nothing in MyTestLog in Windows EventLog. Is there anything I missed?

like image 572
David Tsui Avatar asked Dec 04 '19 10:12

David Tsui


People also ask

How do I inject a logger in .NET Core?

So, go to the Startup. cs file and add the ILoggerFactory parameter in the Configure() method. Then, call the AddFile() extension method to add Serillog file provider, as shown below. ASP.NET Core dependency injection will automatically pass an instance of the LoggerFactory for this parameter.

Where does ILogger write to?

ILogger offers provider-based functionality to write to the console, the debug window, the Windows Event Log, to Microsoft Azure Ap Services diagnostics and logs, as well as to the TraceSource and the EventSource.


3 Answers

You can go for a configuration only approach, leaving your existing CreateHostBuilder code as-is.

As mentioned in the document you linked, under the Windows Eventlog section, the EventLogProvider defaults to the warning level when not explicitly configured:

Unlike the other providers, the EventLog provider does not inherit the default non-provider settings.
If EventLog log settings aren't specified, they default to LogLevel.Warning.

To lower this logging level to Information, you have to foresee an explicit entry for the EventLog provider in the Logging section of your appsettings.{Environment}.json file.

E.g.: appsettings.Development.json:

{
    "Logging": {
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        },
        "EventLog": {
            "LogLevel": {
                "Default": "Information"
            }
        }
    }
}
like image 172
pfx Avatar answered Nov 14 '22 23:11

pfx


It's caused by Host.CreateDefaultBuilder(args), which executes:

.ConfigureLogging(loggingBuilder => {
    loggingBuilder.AddFilter<EventLogLoggerProvider>((Func<LogLevel, bool>) (level=>level>=LogLevel.Warning));
}

under the hood. Warning is 1 level higher than Information, so...

As a solution, you can create fresh HostBuilder using new HostBuilder() and configure it from scratch or override that behavior by calling .ConfigureLogging after creating default host builder.

like image 26
Gio Tabidze Avatar answered Nov 15 '22 00:11

Gio Tabidze


Try bumping up your logging to _logger.LogError("GetServerInfo Called"") and see if it works. If it does, then you will have to set up your log filtering

like image 37
Paul Lorica Avatar answered Nov 14 '22 22:11

Paul Lorica