c# - 动态设置文件名时,未使用 NLog 创建日志文件

标签 c# logging nlog

我正在使用以下 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/

相关文章:

c# - 最小起订量如何确定使用包含特定值的列表调用的方法

java - 在 Domino Java 代理中使用记录器

c# - 如何将 Microsoft.Extensions.Logging 与 Application Insights 结合使用来记录事件和指标

c# - 当 .Net Thread 没有名称时,如何使用 NLog 打印 threadid 而不是 threadname?

c# - 在没有具体<T>的情况下在.Net core中注入(inject)NLOG?

c# - 从泛型类型调用静态方法

c# - 如何读取 Winform 上的键盘输入?

c# - 检查 Cookie 是否存在

c# - 如何为语义日志记录应用程序 block 组织事件源?

c# - NLog - 条件文件输出