nlog

NLog - ignore certain messages using filters


I want to NLog to ignore certain messages using filters.

from my log file -

2020-07-15 13:18:53.3291 ERROR MyAppName:MyAppName Some other error    
2020-07-15 13:18:53.3291 ERROR MyAppName:MyAppName.BusinessLogic.Notification.ProcessorControl Unknown : Unable to connect for notification control. 
2020-07-15 13:18:53.3291 ERROR MyAppName:MyAppName.BusinessLogic.Notification.ProcessorControl Exception Occurred in Unknown : AggregateException One or more errors occurred.
2020-07-15 13:18:53.3291 ERROR MyAppName:MyAppName Some other error 

from Nlog.config file -

<target xsi:type="File"
        name="file"
        fileName="${var:basedir}/Logs/MyAppName-${shortdate}.log"
        layout="${longdate} [${event-context:item=CC} ${event-context:item=Workstation} ${event-context:item=User} ${event-context:item=IL}] ${level:uppercase=true} ${logger} ${message} ${onexception: ${exception:format=shortType,message,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}}" >
</target>
    ...

<logger name="MyAppName:*" minlevel="Error" writeTo="file" >
      <filters>
        <when condition="contains('${message}','MyAppName.BusinessLogic.Notification')" action="Ignore" />
        <!--<when condition="contains('${message}','*MyAppName.BusinessLogic.Notification*')" action="Ignore" />-->
     </filters>
</logger>

I added filter to ignore any messages that may contain the string
"MyAppName.BusinessLogic.Notification" but it's not working.
I also tried with *MyAppName.BusinessLogic.Notification* as in the commented line - but my log file is still filled with these messages.
Can anyone please guide how can I fix this?

One more question - Doesn't $message represents complete error message, like this from log file -

MyAppName:MyAppName.BusinessLogic.Notification.ProcessorControl Unknown : Unable to connect for notification control. 

Thank you!


Solution

  • "MyAppName.BusinessLogic.Notification" is probably not in your ${message}, but it's your logger name (${logger})

    ${message}

    When writing a log event, here are some example of ${message}

    ${logger}

    The logger name, examples:

    Filtering

    It's easy to filter on the logger name, it's built into the <logger> rule. The name attribute should be read as "filter on name" - * and ? wildcards are supported.

    Example:

    <rules>
        <logger name="MyAppName.BusinessLogic.*" minlevel="Error" writeTo="ErrorWithBusinessLogicStuffTarget" />
    

    Read more here

    Notes