You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NLog v5中FileTarget写入网络路径生成编号文件问题

NLog生成编号日志文件问题解决

问题根源

你遇到的是NLog 5.x的新特性:当写入网络路径文件时,如果无法获取独占写入锁(比如文件被其他进程占用、网络权限不足),NLog会自动生成带编号的备用文件,这是5.x版本新增的文件访问容错机制,和4.x版本的处理逻辑不一样。

解决办法

要强制NLog只写入目标文件,不生成编号文件,给jsonInfo目标添加以下配置项:

  • concurrentWrites="false":禁用并发写入,确保单进程独占文件(多进程写入场景不要用这个)
  • allowFileSharedWriting="true" + fileShare="ReadWrite":允许共享写入,避免因锁触发备用文件逻辑
  • openFileCacheTimeout="0":关闭文件缓存,避免缓存导致的状态判断错误
  • enableArchiveFileCompression="false":明确禁用归档(排除干扰)

同时务必检查网络路径权限:运行服务的账号必须对\\***\logs\目录有完全控制权限,包括共享权限和NTFS权限,缺一不可。

修改后的配置示例

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true">

  <targets>
    <!-- JSON Info Logging -->
    <target name="jsonInfo" xsi:type="File" 
            fileName="\\***\logs\sending.json" 
            enableFileDelete="false" 
            replaceFileContentsOnEachWrite="false" 
            deleteOldFileOnStartup="false"
            concurrentWrites="false"
            allowFileSharedWriting="true"
            fileShare="ReadWrite"
            openFileCacheTimeout="0"
            enableArchiveFileCompression="false">
      <layout xsi:type="JsonLayout">
        ...
      </layout>
    </target>
    <!-- JSON Error Logging -->
    <target name="jsonError" xsi:type="File" fileName="\\***\logs\error.json">
      ...
      </layout>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" maxlevel="Info" writeTo="jsonInfo" />
    <logger name="*" minlevel="Warn" writeTo="jsonError" />
  </rules>
</nlog>

额外排查方向

  • 回退4.x版本仍有问题,大概率是网络路径的权限或文件锁问题,比如服务账号变更、共享权限被修改,或者有备份/监控进程在占用sending.json
  • 如果是多进程同时写这个文件,共享写入可能会导致日志乱序,这种情况建议换用NetworkTarget或者分布式日志方案,不要硬扛单文件写入

内容的提问来源于stack exchange,提问作者ndcHunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 08:54:54