Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ILogger Interface not logging everything into Event Log / Core 3.0

I'm trying to log anything that my application outputs(including information messages) into the event log, but the ILogger interface only writes warnings and above there.

Here is my program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureLogging((context, logging) =>
    {
        logging.ClearProviders();
        logging.AddConsole();
        logging.AddEventLog(context.Configuration.GetSection("Logging:EventLog").Get<EventLogSettings>());
        logging.SetMinimumLevel(LogLevel.Information);
    });

My appsettings.json:

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "LogName": "Application",
      "SourceName": "My cool App"
    }
  }

In my application I do the following:

_logger.LogInformation("test information");
_logger.LogWarning("test warning");
_logger.LogDebug("test debug");
_logger.LogError("test error");
_logger.LogTrace("test trace");
_logger.LogCritical("test critical");

In the console output I receive all of the test messages. But in the event log I only get Warning, Error and Critical.

What am I doing wrong here?

like image 478
AnKing Avatar asked Mar 24 '20 14:03

AnKing


1 Answers

in the event log I only get Warning, Error and Critical.

From this documentation, you can find that events would be logged for Warning level and higher when we use Microsoft.Extensions.Logging.EventLog.

To log events lower than LogLevel.Warning, please set the log level explicitly, like below.

"EventLog": {
  "LogLevel": {
    "Default": "Trace"
  }
}

Besides, please note that the trace log messages may contain sensitive application data and so shouldn't be enabled in a production environment.

And from the source code of EventLogLogger.cs as below, we can find that it would use Information, Warning, and Error as EventLog EntryType based on LogLevel to write EventLog(s).

    private EventLogEntryType GetEventLogEntryType(LogLevel level)
    {
        switch (level)
        {
            case LogLevel.Information:
            case LogLevel.Debug:
            case LogLevel.Trace:
                return EventLogEntryType.Information;
            case LogLevel.Warning:
                return EventLogEntryType.Warning;
            case LogLevel.Critical:
            case LogLevel.Error:
                return EventLogEntryType.Error;
            default:
                return EventLogEntryType.Information;
        }
    }

Test Result

_logger.LogTrace("test trace1");

enter image description here

like image 111
Fei Han Avatar answered Oct 23 '22 03:10

Fei Han