I can’t say that I really tried this, but you could use filtering and condition to achieve what you want.
Here is an example condition
page:
<rules> <logger name="*" writeTo="file"> <filters> <when condition="length(message) > 100" action="Ignore" /> <when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" /> <when condition="(level >= LogLevel.Debug and contains(message,'PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" /> <when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" /> </filters> </logger> </rules>
To achieve your goal, you can do a filter
like this:
<rules> <logger name="*" writeTo="file"> <filters> <when condition="length('${exception}') > 0" action="Log" /> </filters> </logger> </rules>
The idea is that you only want to register a message if the length of the exception string is> 0. Some examples of when condition
used the NLog LayoutRenderer syntax (like ${message}
), and some didn't (like message
). I'm not sure if this is correct or what syntax to use in which situation. An example that I posted directly above can lead to messages being logged ONLY if there is an exception. You should also be configured so that your messages for one purpose are logged “normally”, and messages to your “ExceptionHoneypotTarget” are logged only if an exception is present.
Maybe something like this:
<rules> <logger name="*" writeTo="ExceptionHoneypot"> <filters> <when condition="length('${exception}') > 0" action="Log" /> </filters> </logger> <logger name="*" writeTo="file"> </logger> </rules>
As I mentioned before, I actually did not try anything, but it looks like you should do it, hopefully it looks like what was shown above.
Alternatively, you can use FilteringWrapper around your HoneypotTarget. The configuration might look something like this:
<?xml version="1.0" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="Honeypot" xsi:type="FilteringWrapper" condition="length('${exception}')>0"> <target xsi:type="File" fileName="${basedir}/Honeypot.txt" /> </target> <target name="normal" xsi:type="File" fileName="${basedir}/Log.txt" /> </target> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="Honeypot,normal" /> </rules> </nlog>
I based the FilteringWrapper
example on an example from here . The way it should work, if my configuration is correct, is that all messages will be logged in "Log.txt", and messages with a non-empty exception will be recorded in "Honeypot.txt".