0

I'm using nLog 2.0 and after this interesting read I tried to apply conditions to a simple layout as such:

layout="${message:when=logger==A}"
layout="${message:when=logger=='A'}"
layout="${message:when='logger==A'}"

Not only do none of these have any effect, they also do not throw an error so it seems the condition is silently swallowed somewhere (throwExceptions is set to true)

  1. How to conditional layouts to work? Do they even work
  2. Can nLog throw exceptions if something is wrong/unrecognized?

Here is the full code, this is a basic console application.

main.cs:

class Program
{
  static void Main( string[] args )
  {
    NLog.LogManager.GetLogger( "A" ).Info( "from A" );
    NLog.LogManager.GetLogger( "B" ).Info( "from B" );
  }
}

NLog.config (in executable directory):

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

  <targets>
    <target name="main" xsi:type="File" fileName="my.log"
            deleteOldFileOnStartup="true" keepFileOpen="true"
            layout="${callsite} ${message:when=logger=='A'}"/>
   </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="main" />
  </rules>
</nlog>

Output:

ConsoleApplication1.Program.Main from A  -> this should only log ${callsite}
ConsoleApplication1.Program.Main from B
stijn
  • 34,664
  • 13
  • 111
  • 163

1 Answers1

1

Thanks! Try to set logger name:

<logger name="A" minlevel="Trace" writeTo="main" />
<logger name="B" minlevel="Trace" writeTo="main" />

Now there are two loggers, they are available in the code - conditions should work.

kolbasov
  • 1,548
  • 11
  • 15
  • this does not have the desired effect: while it will not log messages from any logger but A, it does so because all other loggers are simply rejected, not because of the conditional format. I updated the question to make this more clear. – stijn Dec 05 '11 at 13:01
  • If I understand nlog config right when you use GetLogger("A") it must be configured as . Therefore, you should add configuration for both loggers. Please, see updated answer. – kolbasov Dec 05 '11 at 13:14
  • that's not true, you can use wildcards to select loggers. http://nlog-project.org/wiki/Configuration_file#Rules – stijn Dec 05 '11 at 13:17
  • hm, I've tried your code and it's worked. Check it https://github.com/kolbasov/NLogTest – kolbasov Dec 05 '11 at 17:07
  • +1 thanks for checking that out. And yes indeed it works: your version of NLog.dll is newer than mine (my build was from june, just tried latest stable from the site and that is from july and does work), so that was the problem all along. – stijn Dec 05 '11 at 21:58