Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different NLog Instance In Order to Separate NLog configuration in different config files

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.

like image 207
superhuman1314 Avatar asked Dec 06 '16 09:12

superhuman1314


People also ask

How do you use NLog for multiple projects in the same solution?

If you want to log in other projects within the solution, just reference NLog. dll directly in each of the projects and use it. But now you only need to configure NLog in your main application. The configuration will then be shared automatically across all projects that reference NLog.

What can be configured with this NLog config file?

The following types can be configured: Targets - the destinations of a logevent, e.g. file, database, console. Layout - the layout e.g. json, csv, plain-text (default) Layout renderers - the template markers, e.g. ${message}, ${exception}, ${date}


1 Answers

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}/nlog2.config"/>

  ...
</nlog> 

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

like image 122
Julian Avatar answered Sep 19 '22 08:09

Julian