繁体   English   中英

当应用程序是默认处理程序时,NLog将日志文件写入不正确的目录

[英]NLog Writing Log File to Incorrect Directory when Application Is Default Handler

我遇到了一个奇怪的问题,我想知道它是配置还是错误。 我在网上找不到任何东西,所以这就是问题所在。 我的问题是如何写入可执行目录而不是启动目录。

重现步骤:

  1. 创建带有日志记录的应用程序( C:\\Program Files\\FooBar\\FooBar.exe
  2. 使此应用程序成为特定文件类型( *.bar )的默认处理程序
  3. 双击特定文件类型的文件( C:\\Desktop\\foo.bar )启动应用程序
  4. 日志文件将被写入文件目录,而不是执行目录。 C:\\Desktop\\log.txt而不是C:\\Program Files\\FooBar\\log.txt 。)

难道我做错了什么? 当我先启动应用程序然后加载文件时,日志记录会在正确的目录中进行。 我的代码和配置非常简单:

public partial class Form1 : Form {
    private static Logger logger = LogManager.GetCurrentClassLogger();

    public Form1() {
        InitializeComponent();
        MessageBox.Show("Continue");
    }
}

和配置:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
  autoReload="true"
  throwExceptions="false"
  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
  <targets>
    <target name="logfile" xsi:type="File" fileName="FooBar.txt" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />    
  </rules>
</nlog>

我放置了一个调试器,以查看Assembly.GetExecutingAssmebly()的位置,并将其放在正确的位置( C:\\Program Files\\FooBar\\foobar.exe )。 因此,我不确定NLog为什么将日志与启动文件的文件而不是可执行目录本身一起写入目录。

它将写入执行的位置,因为那是应用程序的当前工作目录

要解决此问题,请在目标文件名中使用类似${basedir} ,例如:

<target
  xsi:type="File"
  name="File"
  fileName="${basedir}/logs/${shortdate}.log"
  layout="${level:uppercase=true} ${longdate} ${message} ${exception:format=ToString}"
  encoding="utf-8"
  />

这会将日志输出到一个名为logs的文件夹,您的应用程序将从该文件夹中执行(假设它具有写权限)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM