How can i handle own error codes with NLOG logging

Viewed 35

Hi i try to Log error codes like in Log4Net

$logger.Error(3, "Converting task invocator's config file failed, exiting...")

If this error occurs it logs only the Error code "3" but not the message. it Looks like it takes the Error code as text und drops the message it self.

EventLog --> [TaskV1] (Automation_TaskInvocator.ps1 - 1.0.0.0) [] [ERROR] 3 --> message is missing Same problem with Database and file.

the question is how i can handle that. it should takes the error Code as INT and the Message as text. I don't want to go over my hundreds of lines of code to add the error code to the message. especially since I have an extra column for the error codes in the database.

Hope someone can bring me on the right way

thanks a lot

With best regards

1 Answers

Example of custom extension-method for NLog-ILogger (Not tested with a compiler, so might need some tweaks):

public static class NLogLoggerExtensions
{
    public static void Error(this NLog.ILogger logger, int eventId, string message)
    {
        Log(logger, NLog.LogLevel.Error, eventId, null, message);
    }

    public static void Error(this NLog.ILogger logger, int eventId, Exception exception, string message)
    {
        Log(logger, NLog.LogLevel.Error, eventId, exception, message);
    }

    private static void Log(NLog.ILogger logger, NLog.LogLevel loglevel, int eventId, Exception exception, string message)
    {
        var logEvent = NLog.LogEventInfo.Create(loglevel, logger.Name, exception, message);
        if (eventId != 0)
            logEvent.Properties["EventId"] = eventId;
        logger.Log(logEvent);
    }
}

You could also inject the "EventId" as a property like this:

logger.WithProperty("EventId", 3).Error("Converting task invocator's config file failed, exiting...")

Or using Fluent API like this:

logger.ForErrorEvent().Property("EventId, 3").Message("Converting task invocator's config file failed, exiting...").Log();

See also: https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer

Related