Implementing a Custom ILogger with Exception Handling for .NET Core

,

This article corresponds with the MSDN article: Essential .NET – Logging with .NET Core. This github repo contains the code referenced in the article. Not in particular the unit test LogCritical_Exception_Success for an example of handling an exception using the custom logger.

The Custom Logger implementation is straightforward:

Here is the the extension method for adding a custom logger provider:

The custom logger provider:

The provider event args

One uses the ApplicationLogging static class to set up the custom logger with the following pattern

Share this story

7 responses to “Implementing a Custom ILogger with Exception Handling for .NET Core

  1. How do I pass and read custom object in the log method implementation of my custom logger?

    // Write log message
    myCustomLogger.LogError(“My Message”, customDataObject);

    // Log method implementation
    public void Log(…)

    In other words, How do I read customDataObject in above Log method?

    Thanks in advance.

    1. string formatter(Message msg, Exception ex)
      {
      var content = $”[{logLevel}]\r\n{msg.Title}\r\n{msg.Body}\r\n{msg.Author}\r\n{msg.CreatedDate}\r\n\r\n”;
      return content;
      }
      log.Log(logLevel, new EventId(), message, null, (msg, ex) => formatter(msg, ex));

      where Message is a custom object -> in yout custom provider, “TState state” parameter of Log method will be your passed object

  2. How does this handle exceptions? I was kind of thinking that CustomLogger.Log() would implement try/catch logic to handle exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *