Search code examples
c#asp.net-corenlog

How to add filter condition for NLog Target


I have a problem I have write a Nlog.target to log in database but I want nlog should log depending on a condition. I want to put a condition if dbvalue is true then made log entries in db. I wrote the below code which is not working the dbvalue is false but log are still generated in db.

i have added this line in my startup.cs file GlobalDiagnosticsContext.Set("dbvalue", "false");

here is my nlog.config

<rules>
   <logger name="Microsoft.*" maxlevel="Info" final="true" writeTo="" />
 
   <logger name="*" minlevel="Info" writeTo="database" >
      <filters>
         <when condition="equals('${gdc:dbvalue}', 'true')" action="Log" />
      </filters>
   </logger>
</rules>

can someone help?


Solution

  • I would probably do it like this:

    <rules>
       <logger name="Microsoft.*" maxlevel="Info" final="true" writeTo="" />
     
       <logger name="*" minlevel="${gdc:dbLogMinLevel:whenEmpty=Off}" writeTo="database" />
    </rules>
    

    And then enable the database-logger like this:

    NLog.GlobalDiagnosticsContext.Set("dbLogMinLevel","Info");
    NLog.LogManager.ReconfigExistingLoggers(); // Explicit refresh active Logger-objects
    

    See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

    See also: https://github.com/NLog/NLog/wiki/Environment-specific-NLog-Logging-Configuration