Farukh
Farukh

Reputation: 2223

NLog 2.1 EventId for EventLog not working when not specified

I am using Nlog 2.1 and trying to write errors into Windows Event logger with different eventId. To better distinguish different errors. If I specify eventId property it's working, but if don't I am not seeing any record in Windows Event Logger.

NLog.config file:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

<targets>

<target name="console" xsi:type="ColoredConsole"
        layout="${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message}" />

<target xsi:type="EventLog"
    name="eventlog"
    layout="{${newline}
    &quot;Logger&quot;: &quot;${logger}&quot;,${newline}
    &quot;StackTrace&quot;: &quot;${stacktrace}&quot;,${newline}
    &quot;Message&quot;: &quot;${message}&quot;,${newline}
    &quot;Exception&quot;: &quot;${exception:format=ToString,Data}&quot;${newline}}"
    machineName="."
    source="CareFusion Analytics Agent Service"
    eventId="${event-properties:EventID}"
    log="Application" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="console" />
    <logger name="*" minlevel="Error" writeTo="eventlog" />
  </rules>
</nlog>

Usage:

private static void Main(string[] args)
    {
        Logger logger = LogManager.GetCurrentClassLogger();

        logger.Error("Sample error message"); //This is not working

        LogEventInfo logEvent = new LogEventInfo()
        {
            Level = LogLevel.Error,
            Message = "Hello",                
            LoggerName = logger.Name

        };
        logEvent.Properties.Add("EventID", 400);

        logger.Log(logEvent);  //This is working


        Console.WriteLine("Press any key....");
        Console.ReadKey();
    }

Upvotes: 1

Views: 943

Answers (1)

Julian
Julian

Reputation: 36700

The call logger.Error("Sample error message"); goes wrong as the EventLogTarget tries to convert the ${event-properties:EventID} to a integer.

Because layout renders in NLog never return null (but string.Empty), this will give a exception - which will be caught by NLog. In the NLog's internal log you should see a FormatException.

So we need to specify a default value, you could do that with the whenEmpty:

<target xsi:type="EventLog"
        ...
        eventId="${event-properties:EventID:whenEmpty=0}"  /> 

PS: tested it with NLog 4.3.11

Upvotes: 1

Related Questions