我正在使用以下 NLog 配置,并删除了 FileName 属性。我想动态设置它。我也为其编写了代码。但它根本不会在指定位置创建日志文件。
如果我在任何地方出错,请告诉我。
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="console" xsi:type="Console" />
<target name="logfile" xsi:type="File"
layout="${longdate} ${level} ${message}" archiveAboveSize="1048576"
concurrentWrites="true"
keepFileOpen="false"
encoding="iso-8859-2" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
动态设置文件名的 C# 代码:
LoggingConfiguration config = new LoggingConfiguration();
FileTarget fileTarget = new FileTarget();
config.AddTarget("logfile", fileTarget);
fileTarget.FileName = @"C:\Logfile\Log.txt";
NLog.LogManager.Configuration = config;
LoggingRule rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule);
但日志文件 Log.txt 未在 C:\Logfile> 中创建。也没有抛出异常
非常感谢任何帮助。提前致谢。
最佳答案
我很确定您正在通过代码覆盖您的配置。为什么不在代码中配置所有内容?
您确定您拥有写入C:\Logfile\Log.txt
所需的权限吗?
我刚刚尝试过你的代码,它对我有用。
您还可以启用 NLog 的内部日志记录:https://github.com/nlog/NLog/wiki/Internal-logging
关于c# - 动态设置文件名时,未使用 NLog 创建日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840719/