简体   繁体   中英

NLog - 2 separate log files - How to write to one or the other

I want to explicitly write to 2 different log files . Based on the method or type of operations.

How to?

I have seen the following StackOverFlow post Having NLog loggers with different configuration

How do I configure NLog? What code do I need too, so I can write to 1 file or the other? using code like: log.Error("My Big Error") ;

The post contains the following

<targets> 
    <target name="f1" xsi:type="File" fileName="${logger}.txt" />
    <target name="f2" xsi:type="File" fileName="${shortdate}.txt" />
</targets>

So, if it's 'general error' I want write to f1 . If it's file operation error I want to write to f2

thx in advance

In the NLog configuration you need to set up some rules to write to the targets (otherwise nothing get logged). In those rules you could add filters and conditions.

Simple example

For example:

<rules>
  <logger name="Logger1" writeTo="f1" />
  <logger name="Logger2" writeTo="f2" />
</rules>

The name attribute is here a filter, so the first rule means: write to f1 if logger name is equals to "Logger1". The rules are processed from top to bottom.

So when calling LogManager.GetLogger("Logger1").Info("My message") this will write to target f1 and LogManager.GetLogger("Logger2").Info("My message") will write to target f2 .

GetCurrentClassLogger

When using LogManager.GetCurrentClassLogger() , the logger name is constructed of the current class and namespace name, eg "MyNameSpace.MyClass". This means you could adjust the name attribute to name="MyNameSpace.MyClass" , or name="*.MyClass" for matching.

Final

You could also write this:

<rules>
  <logger name="Logger1" writeTo="f1" final="true" />
  <logger name="*" writeTo="f2" />
</rules>

This will write events of Logger1 to f1 , and others to f2 . You probably need the filter attribute, otherwise also the events of Logger1 will be written to f2 - and that isn't always what you need.

Other filter rules

There are many more filter options, eg min level, max level, but also more advanced filters (not only on logger name). You could read more about that here

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