【问题标题】:make NLog.config file load the file from (d:\dev) instead of "\bin\debug\"使 NLog.config 文件从 (d:\dev) 而不是 "\bin\debug\" 加载文件
【发布时间】:2013-04-04 04:59:50
【问题描述】:

我使用 Nlog 在特定的 DLL 中进行日志记录。然后在另一个应用程序中使用 DLL(它使用 System.Reflection.Assembly.LoadFrom(path + a.dll) 动态加载)。我手动将 Nlog.dll 和 Nlog.config 文件放在 Path 文件夹中,应用程序可以正常执行,但它没有记录任何消息。

但是,当我继续将 Nlog.config 文件手动放置在应用程序目录 (\bin\debug\) 中时,会记录消息。

谁能告诉我如何将 Nlog.Config 的搜索位置指向除 \bin\debug\ 之外的其他目录 (d:\dev)。

【问题讨论】:

    标签: c# configuration configuration-files nlog nlog-configuration


    【解决方案1】:

    NLog 配置需要驻留在运行动态拉取 a.dll 的应用程序所在的文件夹中。 如果您正在调试,这就是为什么将它放入 bin\debug 时它可以工作的原因。 如果您使用的是 Visual Studio,请尝试将您的 nlog.config 设置为“始终复制”,它应该会放在您需要的地方。

    【讨论】:

    • 感谢@jim 的回复。我确实在应用程序 X 的项目“a”中将 Nlog.config 设置为“始终复制”,并将其复制到应用程序 X 的“\bin\debug\”文件夹。但我在一个全新的应用程序中使用了 a.dll (Y) 并希望它转到应用程序 Y 的“bin/debug”或进行更改,以便在“d:\dev”文件夹中查找 Nlog.config
    【解决方案2】:

    请参阅 NLog wiki 上的 Configuration file locations

    NLog 定位配置的方式基本上是:

    • 标准应用程序配置文件(通常是applicationname.exe.config)
    • 应用程序目录中的applicationname.exe.nlog
    • 应用程序目录中的 NLog.config
    • NLog.dll.nlog 在 NLog.dll 所在目录中(仅当 NLog 不在 GAC 中时)
    • NLOG_GLOBAL_CONFIG_FILE 环境变量指向的文件名(如果已定义,仅限 NLog 1.0 - NLog 2.0 中已删除支持)

    没有其他方法可以做到这一点。

    【讨论】:

    • 一种方法可以做到这一点,see above
    【解决方案3】:

    以下是我如何更改 Nlog 的配置以指向 Executing Assembly 文件夹中的 Nlog.config 文件。

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

    【讨论】:

    • 你可以使用 Path.Combine(assemblyFolder, "NLog.config")
    【解决方案4】:

    我发现了

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

    实际上将记录器指向要记录到的文件,而不是配置文件。这样做的好处是,您可以定义日志文件路径而无需知道 ExecutingAssembly - 这在使用 ExcelDNA 等时特别有用,因为 XLL 将程序集作为比特流动态加载,所以

    Assembly.GetExecutingAssembly().Location
    

    抛出异常。

    【讨论】:

      【解决方案5】:

      您可以在 NLog.config 中使用包含文件。拥有一个简单的 NLog.config,其中仅包含来自 D:\DEV 的 NLog.config。

      例如:

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

      您也可以使用 app.config 来实现。例如:

      <?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>
      

      另请参阅:https://github.com/nlog/nlog/wiki/Configuration-file#include-files

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多