简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM