6
votes

Currently i am facing NLog.Configuration overwritten issue if i point LogManager.Configuration to different config file.

Is it possible to create multiple NLog instance in same project to prevent sharing same LogManager.Configuration?

Something like :

FruitType class has own NLog instance, its NLog.LogManager.Configuration is read from default nlog.config.

Then, i would like to configure sub-class to be something as follow:

Apple class instance has own NLog instance and Apple class NLog.LogManager.Configuration is read from AppleNLog.config instead of nlog.config.

then new fruit

Orange class instance has own NLog instance and Orange class instance NLog.LogManager.Configuration is read from OrangeNLog.config instead of nlog.config.

The reason i want to do this is to separate the nlog rule into different config file instead of default nlog.config to micro-manage nlog configuration.

1

1 Answers

6
votes

There are two ways to accomplish this:

a. Create separate living LogFactory objects and separate the config.

e.g.

public static class MyLogManager
{
    static public NLog.LogFactory Factory1 = new LogFactory(new XmlLoggingConfiguration("nlogconfig1.xml"));
    static public NLog.LogFactory Factory2 = new LogFactory(new XmlLoggingConfiguration("nlogconfig2.xml"));
}

Usage:

var logger1 = MyLogManager.Factory1.GetCurrentClassLogger();
//or
var logger2 = MyLogManager.Factory2.GetCurrentClassLogger();

b. Less separated, but still modular config files, use <include> e.g. nlog.config

<nlog>
  ...
  <include file="${basedir}/nlog1.config"/>      
  <include file="${basedir}/nlog1.config"/>

  ...
</nlog> 

nlog1.config and nlog2.config contain the regular <targets> and <rules>. But be aware of potential name clashes of the targets.