C# NLog 不创建日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10550788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NLog does not create a log file
提问by Srv19
I am trying to add logging to an application running on mobile device with Windows Mobile 6.1. ? .NET Compact framework 3.5. using NLog.
我正在尝试向运行在 Windows Mobile 6.1 移动设备上的应用程序添加日志记录。? .NET 紧凑型框架 3.5。使用 NLog。
I have the appropriate version of the NLog distribution installed.
我安装了相应版本的 NLog 发行版。
However no log files are being created.
但是,没有创建日志文件。
Here is my NLog.configfile:
这是我的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();
}
采纳答案by Srv19
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}布局渲染器作为文件名的一部分被证明是一种解决方案。
回答by Mauricio Gracia Gutierrez
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
回答by Malcolm Anderson
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. (I've reformatted the paragraph a little for better readability.) https://github.com/NLog/NLog/wiki/Logging-troubleshooting
我遇到了这个问题,结果我的日志文件没有被复制到我的构建目录中。NLog github 页面给出了答案。(为了更好的可读性,我重新格式化了段落。) https://github.com/NLog/NLog/wiki/Logging-troubleshooting
NLog cannot find the configuration file. 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 找不到配置文件。当 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)
设置构建操作 = 内容和“复制到输出目录 = 如果更新则复制以解决此问题)
回答by Chris Halcrow
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 instancee.g. if you're running in debug mode, you'll see log.txt in your bin > debug folder. (This isn't explained very clearly in the troubleshooting guide).
此规则将匹配您创建的任何记录器,如果它有效,它将在“基本目录”中放置一个 log.txt 文件 - 这是您的测试实例的“bin”目录,例如,如果您正在调试中运行模式,您将在 bin > debug 文件夹中看到 log.txt。(这在故障排除指南中没有很清楚地解释)。
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" 还可以确保您在调试时获得有用的错误消息。
回答by Jayendran
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>
回答by Prem Kumar Badri
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
回答by Jabez
for simple troubleshooting purposes, launch VisualStudio to run as administrator. This will help to sort out permissions to create log files while debugging.
出于简单的故障排除目的,启动 VisualStudio 以管理员身份运行。这将有助于在调试时理清创建日志文件的权限。
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 自动在目标部分提供的文件路径中创建丢失的文件夹。
回答by Sapnandu
I also faced the same issue, finally i have solved it. I had a web application, where i want to implement NLog. Please find the following steps to implement NLog.
我也遇到了同样的问题,终于解决了。我有一个 Web 应用程序,我想在其中实现 NLog。请找到以下步骤来实现 NLog。
Step 1:- Go to NuGet packages manager and install following packages.

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.
我们已经做到了。现在执行您的代码并享受日志记录。
回答by Alex Stephens
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 中为网站修复它的方法:
- Right click on your folder in windows explorer and select properties
- Choose the securitytab
- Click edit
- Click add
- In the textbox type 'IIS AppPool\YourAppPoolName' replace YourAppPoolName with the actual name of the application pool your site runs under
- Click Check names
- Click OK
- 在 Windows 资源管理器中右键单击您的文件夹并选择属性
- 选择安全选项卡
- 点击编辑
- 点击添加
- 在文本框中键入“ IIS AppPool\YourAppPoolName”,将 YourAppPoolName 替换为您的站点在其下运行的应用程序池的实际名称
- 单击检查名称
- 单击确定
Security footnote: From a security aspect the best practice is to use ApplicationPoolIdentity as it is a dynamically created, unprivileged account. more reading here: https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities
安全脚注:从安全方面来看,最佳做法是使用 ApplicationPoolIdentity,因为它是一个动态创建的非特权帐户。更多阅读:https: //docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

