Search code examples
c#logging.net-corenlogmicrosoft-extensions-logging

Creating custom extension functions for logging with NLog


I am using NLog in a .Net Core 2.2 project.

I want to implement a category system for my logs using EventId (supported in NLog).

Currently I am using the logger like this:

logger.LogInformation(new EventId(5, "UserLogin"), "The user: {username} logged in.", username);
logger.LogInformation(new EventId(6, "UserChangedPassword"), "The user: {username} changed their password.", username);

But I would much prefer to be able to use it like this:

logger.LogUserLogin(username);
logger.LogUserChangedPassword(username);

Where LogUserLogin and LogUserChangedPassword are custom functions that would add in the correct EventId id and name and then log the event as LogInformation.

My questions are:

  1. How can I extend the logger with my custom functions?
  2. Is this the wrong/non-ideal way to implement a category system for NLog? Should I rather define the EventId as I'm writing the logs, like I'm doing currently?

I feel like this should be relatively simple, but my googling skills seem to be failing me at the moment.


Solution

  • The LogInformation is from the Microsoft abstraction (not NLog), but no problem!

    Just write two C# extension methods:

    /// <summary>
    /// Extensions for <see cref="Microsoft.Extensions.Logging.ILogger"/>
    /// </summary>
    public static class LoggerExtensions
    {
        public static void LogUserLogin<T>(this ILogger<T> logger, string username)
        {
            logger.LogInformation(new EventId(5, "UserLogin"), "The user: {username} logged in.", username);
        }  
    
        public static void LogUserChangedPassword<T>(this ILogger<T> logger, string username)
        {
            logger.LogInformation(new EventId(6, "UserChangedPassword"), "The user: {username} changed their password.", username);
        }
    }
    

    Is this the wrong/non-ideal way to implement a category system for NLog? Should I rather define the EventId as I'm writing the logs, like I'm doing currently?

    I think this is a nice way. There are other ways to do abstractions but this is IMO not a bad choice.