【发布时间】:2018-10-01 07:39:12
【问题描述】:
我有一个 .NET 应用程序。我正在尝试使用 NLog 编写一些日志。我的应用程序非常基本并且成功运行而不会引发异常。但是,我在任何地方都看不到实际的日志文件。如何让我的日志真正写入?
MyLogger.cs
using NLog;
public class MyLogger
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public void Log(string message)
{
logger.Info(message);
}
}
Program.cs
static class Program
{
static void Main()
{
var logger = new MyLogger();
logger.Log("hello");
}
}
我在 App.config 文件中添加了 NLog 配置详细信息,如下所示:
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
</appSettings>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logFile" xsi:type="File" fileName="C:\Logs\MyApp.log" keepFileOpen="true" encoding="Utf8" layout="${longdate} ${logger} ${message}${exception:format=ToString}"></target>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logFile" />
<logger name="*" minlevel="Warn" writeTo="logFile" />
</rules>
</nlog>
</configuration>
我没有使用 NLog.config 文件。我的印象是我可以将我的整个配置设置放在 App.config 文件中。我错过了什么?如何使用 NLog 将日志写入文本文件?
谢谢!
【问题讨论】:
-
您是否尝试过在路径中使用正斜杠?
fileName="C:/Logs/MyApp.log" -
我确实尝试在路径中使用正斜杠。但是,这仍然不起作用。
-
Windows 事件日志中有相关信息吗?另外,'c:\logs' 是否已经存在?
-
@NineTails - 我在 Windows 事件日志中看不到任何消息。 C:\Logs 目录确实存在。
-
@Tipx 帮我解决了这个问题。问题是编码。我不得不将编码更改为
utf-8