NLog无法创建日志文件

52

我试图为在运行Windows Mobile 6.1的移动设备上使用.NET Compact Framework 3.5的应用程序添加日志记录,使用NLog。

我已安装了适当版本的NLog分发版。

但是没有创建任何日志文件。

这是我的NLog.config文件:

<?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">
  <targets>
    <target name="logfile" xsi:type="File" fileName=".\Neolant.ASRM.Terminal.log" layout="${longdate}|${level}|${message}|${exception}" autoFlush="true"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>

这里是我使用的测试代码:

public static void Main()
{
    try
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        var logger = NLog.LogManager.GetLogger("UpperLevel");
        logger.Info("test test test.");
        try
        {
            throw new Exception("Unexpected!");
        }
        catch (Exception e)
        {
            var logger = NLog.LogManager.GetLogger("UpperLevel");
            logger.WarnException("An exception occured.", e);
        }
        throw new Exception("Suddenly!");           
    }
    finally
    {
        NLog.LogManager.Flush();
    }
}

private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
    var logger = NLog.LogManager.GetLogger("UpperLevel");
    logger.FatalException("Application closed due to exception.", unhandledExceptionEventArgs.ExceptionObject as Exception);
    NLog.LogManager.Flush();
}

1
你尝试过不同的文件名/路径了吗?例如 fileName="Neolant.ASRM.Terminal.log" 没有 .\\ 前缀?Nlog.Config 文件在应用程序目录中吗?此外,你可以打开 Nlog 的内部日志记录 来获取关于问题的额外信息。 - nemesv
我已经尝试过带有和不带有“.\”的文件名,结果相似(也就是说,没有)。NLog.config已部署到应用程序目录中。现在将尝试内部日志记录。 - Srv19
通过您提供的链接,我偶然发现了解决方案。非常感谢。 - Srv19
我很高兴 :) 然后请将您的解决方案发布为答案,以供后来的访问者参考。 - nemesv
1
这是最新的 NLog 故障排除链接,对于那些通过 Google 搜索进入此处的人来说非常有用... https://github.com/NLog/NLog/wiki/Logging-troubleshooting - SWalters
14个回答

61
我遇到了这个问题,结果发现我的日志文件并没有被复制到构建目录中。NLog的Github页面提供了答案。(为了更好地阅读体验,我对段落进行了重新格式化。)https://github.com/NLog/NLog/wiki/Logging-troubleshooting 当 NLog.config 文件在 Visual Studio 中被配置为 Build Action = None 或 Copy to Output Directory = Do not copy 时,NLog 无法找到配置文件。要解决这个问题,请将 Build Action 设置为 Content,将 "Copy to Output Directory" 设置为 "Copy if newer"。

4
谢谢。 "不复制"设置是问题所在。 - joshmcode
在我的情况下,我正在使用Nlog在appsetings中,它不能创建这个副本吗?而且我遇到了同样的问题,“不创建.log文件”。 - Gabriel Silva

23

日志文件已经被创建 - 但不在应用程序目录中

使用${basedir}布局渲染器作为文件名的一部分被证明是一个解决方案。


嗯,很奇怪。这对我有用,但我有另一个应用程序,在那里不需要指定它(输出仍然有效)。 - Jowen
2
如果你找到了原因,请发帖分享一下。我认为了解NLog日志文件放置的依据会很有帮助。 - Srv19
4
那份文档太糟糕了。你能在回答中举个例子吗? - Joe Phillips
2
请查看Mauricio已经慷慨地提供了另一个答案。 - Srv19

20

2
谢谢,我忘记了将 nlog.config 文件设置为“始终复制”。 我认为如果 nlog 找不到 nlog.config 文件,它应该抛出异常。 - york

17

如果被标记为答案的回复不是十分清晰明了,您可以查看以下示例

<targets>
  <target xsi:type="Console" name="console" 
    layout="${longdate}|${level}|${message}" />
  <target xsi:type="File" name="ErrorLog" fileName="${basedir}/error.txt"
          layout="${longdate}
          Trace: ${stacktrace} 
          ${message}" />
  <target xsi:type="File" name="AccessLog" fileName="${basedir}/access.txt"
          layout="${shortdate} | ${message}" />
</targets>

摘自这里 在NLog中使用AppData位置


9

我的问题与权限相关,日志文件需要允许进程对其进行写入,如果没有写入权限,则无法创建文件。

以下是解决在IIS中的网站问题的方法:

  1. 在windows资源管理器中右键单击文件夹并选择属性
  2. 选择安全选项卡
  3. 点击编辑
  4. 点击添加
  5. 在文本框中输入 'IIS AppPool\YourAppPoolName' 将YourAppPoolName替换为您的网站所在应用程序池的实际名称
  6. 点击检查名称
  7. 点击确定

安全注释: 从安全角度考虑,最佳做法是使用ApplicationPoolIdentity,因为它是动态创建的、无特权的帐户。 更多阅读请参见: https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities


6

来自nlog故障排除指南:

https://github.com/NLog/NLog/wiki/Logging-troubleshooting

如果您知道您的配置文件已经被找到,那么请暂时用以下内容替换NLog.config文件中的<rules>部分,并尝试一下。

此规则将匹配任何您创建的记录器,如果它可以正常工作,则会在'基目录'中放置一个名为log.txt的文件,即您测试实例的'bin'目录。例如,如果您正在以调试模式运行,则将在您的bin > debug文件夹中看到log.txt文件。(这在故障排除指南中没有很清楚地解释)。

如果这个方法有效,那么你就知道问题出在你的规则上了:

<nlog throwExceptions="true">
  <targets>
    <target name="file" type="File" fileName="${basedir}/log.txt" />
  </targets>
  <rules>
    <logger name="*" minLevel="Trace" writeTo="file" />
  </rules>
</nlog>

我发现只有name="file"适用于目标——其他值不行。添加throwExceptions="true",如上所示,还可以确保在调试时获得有用的错误消息。

1
精通编程的相关内容:对我来说,加粗的文本“'bin'目录”非常关键。我没有意识到它在那里。可能是我错过了文档。非常感谢。 - ahong
这也是我的问题,我正在做ASP.NET,{$basedir}是<project_path>\bin\Debug\net5.0(文件夹在Rider Explorer视图中未显示)。 - milos

3
在我的情况下,我在定义规则后错过了规则,但是一旦定义规则,它就像魔法一样起作用。
 <rules>
    <logger name="*" minlevel="Trace" writeTo="logfile" />
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>

晚来的参与者,但这个答案是我的解决方案。 - Abbas

1
我花了很多时间解决这个问题。我的问题是,我使用了一个设置项目将Windows服务与MSI安装在一起。我必须手动将NLog.config添加到安装程序的输出中,以确保它被复制到服务的安装目录中。

0
我也遇到了同样的问题,最终我解决了它。我有一个 Web 应用程序,我想要实现 NLog。请按照以下步骤实现 NLog。
第 1 步:进入 NuGet 包管理器并安装以下包。 enter image description here 第 2 步:打开 Web.config 文件并添加以下行。
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
 <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="D:\projects\NlogWeb\nlog-internal.log">
<targets>
  <target name="console" xsi:type="ColoredConsole" layout="${message}" />
  <!--Write logs to File-->
  <target name="file" xsi:type="File" fileName="D:\projects\NlogWeb\ErrorLogFile.log" layout="--------------------- ${level}(${longdate})${machinename}-------------------- ${newline}
Exception Type:${exception:format=Type}${newline} 
Exception Message:${exception:format=Message}${newline}  
Stack Trace:${exception:format=Stack Trace}${newline}  
Additional Info:${message}${newline}" >
</target>  
</targets>   
<rules>

  <logger name="*" minlevel="trace" writeTo="file" />
</rules>
</nlog>

步骤3:现在是在您的.cs文件中调用最后一个配置。

using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NlogWeb
{
public partial class Home : System.Web.UI.Page
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            throw new Exception("Divide By Zero Exception", new DivideByZeroException());
        }
        catch (Exception ex)
        {                 
            logger.Error(ex.Message);
        }
    }
  }
}

我们完成了。现在执行你的代码并享受日志记录。


0

为了简单的故障排除目的,以管理员身份启动VisualStudio。这将有助于解决在调试时创建日志文件的权限问题。

此外,在每个目标部分中使用createDirs=true,以自动创建目标路径中缺失的文件夹。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接