2016-12-01 17 views
1

我正在使用Nlog 2.1并尝试将错误写入具有不同eventId的Windows事件记录器。更好地区分不同的错误。 如果我指定eventId属性它的工作,但如果我没有看到Windows事件记录器中的任何记录。NLog 2.1 EventId EventLog在未指定时不工作

NLog.config文件:

<?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> 

用法:

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(); 
    } 
+0

你的代码说“不工作”和“工作“,所以它在您构建自己的logeventinfo时起作用? – Julian

+0

是的,它使用LogEventInfo – Farukh

回答

1

呼叫logger.Error("Sample error message");出错的EventLogTarget尝试将${event-properties:EventID}转换为整数。

因为在NLog中渲染的布局永远不会返回null(但是string.Empty),这会产生一个异常 - 它将被NLog捕获。在NLog's internal log中,您应该看到FormatException

因此,我们需要指定一个默认值,你可以做到这一点与whenEmpty

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

PS:有4.3.11 NLOG测试它