سؤال

I used Nlog for logging purpose in a particular DLL. The DLL is then used in another application (it is loaded dynamically using System.Reflection.Assembly.LoadFrom(path + a.dll)). I manually placed Nlog.dll and Nlog.config files in Path folder and the application executes properly but it does not log any messages.

However, when I go ahead and place the Nlog.config file manually in application directory (\bin\debug\) is logs messages.

Can someone let me know how to point the search location for Nlog.Config to a different directory (d:\dev) other than \bin\debug\.

هل كانت مفيدة؟

المحلول

Below is how i changed configuration of Nlog to point to Nlog.config file present in Executing Assembly's folder.

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\NLog.config", true);

نصائح أخرى

See Configuration file locations on the NLog wiki.

Basically the ways NLog locates the config is:

  • standard application configuration file (usually applicationname.exe.config)
  • applicationname.exe.nlog in application’s directory
  • NLog.config in application’s directory
  • NLog.dll.nlog in a directory where NLog.dll is located (only if NLog is not in the GAC)
  • file name pointed by the NLOG_GLOBAL_CONFIG_FILE environment variable (if defined, NLog 1.0 only - support removed in NLog 2.0)

There are no other way to do this.

The NLog config needs to reside in the folder where the app that is dynamically pulling a.dll is running from. If you are debugging, that is why it is works when you put it into bin\debug. If you are using Visual Studio, try setting your nlog.config to 'Copy Always' and it should go where you need it.

I found that

NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(logFilePath, true);

actually points the logger to the file which is to be logged to, not the config file. The great thing about this, is that you can define the log file path without needing to know the ExecutingAssembly - this is especially useful when using ExcelDNA etc as the XLL loads the assemblies dynamically as a bitstream, and so

Assembly.GetExecutingAssembly().Location

throws an exception.

You can use include files with NLog.config. Having a simple NLog.config that only include an NLog.config from D:\DEV.

Ex:

<nlog>
    <include file="D:\DEV\NLog.Config" />
</nlog>

You can also do it with app.config. Ex:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
    </configSections>
    <nlog>
        <include file="D:\DEV\NLog.Config" />
    </nlog>
</configuration>

See also: https://github.com/nlog/nlog/wiki/Configuration-file#include-files

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top