简体   繁体   English

NLog 不创建日志文件

[英]NLog does not create a log file

I am trying to add logging to an application running on mobile device with Windows Mobile 6.1.我正在尝试向运行在 Windows Mobile 6.1 移动设备上的应用程序添加日志记录。 .NET Compact framework 3.5. .NET Compact 框架 3.5。 using NLog.使用 NLog。

I have the appropriate version of the NLog distribution installed.我安装了相应版本的 NLog 发行版。

However no log files are being created.但是,没有创建日志文件。

Here is my NLog.config file:这是我的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>

And here is the test code I was using:这是我使用的测试代码:

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();
}

I had this problem turned out that my log file was not being copied to my build directory.我遇到了这个问题,结果我的日志文件没有被复制到我的构建目录中。 The NLog github page had the answer. NLog github 页面给出了答案。 (I've reformatted the paragraph a little for better readability.) https://github.com/NLog/NLog/wiki/Logging-troubleshooting (为了更好的可读性,我重新格式化了段落。) https://github.com/NLog/NLog/wiki/Logging-troubleshooting

NLog cannot find the configuration file. NLog 找不到配置文件。 This can happen when the NLog.config file is configured with Build Action = None or Copy to Output Directory = Do not copy in Visual Studio.当 NLog.config 文件配置为 Build Action = None 或 Copy to Output Directory = Do not copy in Visual Studio 时,可能会发生这种情况。

Set Build Action = Content and "Copy to Output Directory = Copy if newer to fix this)设置构建操作 = 内容和“复制到输出目录 = 如果更新则复制以解决此问题)

The log file was being created - but not in the application directory.正在创建日志文件 - 但不在应用程序目录中。

Using ${basedir} layout renderer as part of the file name proved to be a solution.使用${basedir}布局渲染器作为文件名的一部分被证明是一种解决方案。

In case the response marked as answer is not all that clear you can check the example如果标记为答案的响应不是很清楚,您可以查看示例

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

Taken from here using AppData location in NLog从这里使用 NLog 中的 AppData 位置获取

from nlog troubleshooting guide来自nlog 故障排除指南

Please check Nlog.config file properties: Copy to output directory should be Copy always请检查 Nlog.config 文件属性:复制到输出目录应始终复制

Please view image link https://i.stack.imgur.com/AlUG5.png请查看图片链接https://i.stack.imgur.com/AlUG5.png

From the nlog troubleshooting guide:从 nlog 故障排除指南:

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

If you know that your config file is definitely being found, temporarily replace the section of your NLog.config file with the following and try it.如果您知道您的配置文件肯定会被找到,请暂时将 NLog.config 文件的部分替换为以下内容并尝试。

This rule will match any logger you've created, and if it works, it will put a log.txt file in the 'base directory' - which is the 'bin' directory for your test instance eg if you're running in debug mode, you'll see log.txt in your bin > debug folder.此规则将匹配您创建的任何记录器,如果它有效,它将在“基本目录”中放置一个 log.txt 文件 - 这是您的测试实例的“bin”目录,例如,如果您正在调试中运行模式,您将在 bin > debug 文件夹中看到 log.txt。 (This isn't explained very clearly in the troubleshooting guide). (这在故障排除指南中没有很清楚地解释)。

If this works then you know that the problem is with your rules:如果这有效,那么您就知道问题出在您的规则上:

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

I found that only name="file" worked for the target - other values didn't我发现只有 name="file" 对目标有效 - 其他值没有

Adding the throwExceptions="true" as above will also ensure that you get useful error messages when you're debugging.如上所述添加 throwExceptions="true" 还可以确保您在调试时获得有用的错误消息。

My issue was permission related, the log file needs to allow the process to write to it, without write permissions you'll get no file.我的问题与权限有关,日志文件需要允许进程写入它,没有写入权限,您将无法获得任何文件。

Here's how to fix it for websites in IIS:以下是在 IIS 中为网站修复它的方法:

  1. Right click on your folder in windows explorer and select properties在 Windows 资源管理器中右键单击您的文件夹并选择属性
  2. Choose the security tab选择安全选项卡
  3. Click edit点击编辑
  4. Click add点击添加
  5. In the textbox type ' IIS AppPool\\YourAppPoolName ' replace YourAppPoolName with the actual name of the application pool your site runs under在文本框中键入“ IIS AppPool\\YourAppPoolName ”,将 YourAppPoolName 替换为您的站点在其下运行的应用程序池的实际名称
  6. Click Check names单击检查名称
  7. Click OK单击确定

Security footnote: From a security aspect the best practice is to use ApplicationPoolIdentity as it is a dynamically created, unprivileged account.安全脚注:从安全方面来看,最佳做法是使用 ApplicationPoolIdentity,因为它是一个动态创建的非特权帐户。 more reading here: https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities更多阅读: https : //docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

In my case, I've missed the rules after defining the rules works like a charm就我而言,在定义规则后我错过了规则就像魅力一样

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

I also faced the same issue, finally i have solved it.我也遇到了同样的问题,终于解决了。 I had a web application, where i want to implement NLog.我有一个 Web 应用程序,我想在其中实现 NLog。 Please find the following steps to implement NLog.请找到以下步骤来实现 NLog。

Step 1:- Go to NuGet packages manager and install following packages.第 1 步:- 转到 NuGet 包管理器并安装以下包。 在此处输入图片说明

Step 2:- Open Web.config and add those following line第 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>

Step 3:- Now the last configuration to call in your .cs file.第 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);
        }
    }
  }
}

We have done.我们已经做到了。 Now execute your code and enjoy logging.现在执行您的代码并享受日志记录。

To fix this, I had to run my application in administrator mode.为了解决这个问题,我必须以管理员模式运行我的应用程序。 I suspect windows had an update that suddenly prevented exe's from creating a (log) file, since the exe could always prevously log without admin rights.我怀疑 Windows 有一个更新,突然阻止了 exe 创建(日志)文件,因为 exe 之前总是可以在没有管理员权限的情况下登录。

Spent a lot of time on this issue.在这个问题上花了很多时间。 This was my problem.这是我的问题。 I was using a Setup project to install a Windows Service with an MSI.我正在使用安装项目来安装带有 MSI 的 Windows 服务。 I had to manually add NLog.config to the output of the installer to make sure it got copied to the install directory of the service我必须手动将 NLog.config 添加到安装程序的输出中,以确保将其复制到服务的安装目录中

In my case I had to load the NLog.config file manually in the code since it wasn't found automatically.就我而言,我必须在代码中手动加载 NLog.config 文件,因为它没有自动找到。 Loading the configuration must be done before logs are generated.加载配置必须在生成日志之前完成。

LogManager.LoadConfiguration(@"D:\doe\ConsoleApp2\ConsoleApp2\NLog.config");

After that I got log files and console output.之后我得到了日志文件和控制台输出。

in my case, a WebAPI application, I solved the problem by giving modify permissions to IIS_IUSRS the modify permission for the website folder C:\\inetpub\\wwwroot\\my_website在我的例子中,一个WebAPI应用程序,我通过为IIS_IUSRS提供修改权限来解决这个问题,即网站文件夹C:\\inetpub\\wwwroot\\my_website的修改权限

在此处输入图片说明

for simple troubleshooting purposes, launch VisualStudio to run as administrator.出于简单的故障排除目的,启动 VisualStudio 以管理员身份运行。 This will help to sort out permissions to create log files while debugging.这将有助于在调试时理清创建日志文件的权限。

Also use createDirs=true in each of the target section to automatically create missing folders in the file path provided in target section.还可以在每个目标部分中使用 createDirs=true 自动在目标部分提供的文件路径中创建丢失的文件夹。

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

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