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

如何将System.Diagnostics日志通过NLog路由至ElasticSearch

解决System.Diagnostics日志通过NLog路由到ElasticSearch的问题

先明确你的疑问

教程里提到的"application configuration file"确实就是你的app.config(如果是Web项目则对应web.config)。


问题分析与解决方案

1. app.config配置方式的问题

你当前的app.config仅配置了System.Net和System.Net.Sockets的TraceSource监听,但默认Trace.WriteLine这类日志不会走这些Source;且默认的DefaultListener会直接输出到控制台,你看到的堆栈是它的输出,并非NLog处理的日志。

要让System.Net的日志进入NLog,需要确保:

  • 移除DefaultListener避免重复输出
  • 确认NLog规则能捕获到对应Source的日志(你的name="*"规则已经覆盖,但可以更明确)

2. 代码方式的修复(推荐,符合你的需求)

直接添加NLogTraceListener无输出的原因是缺少开关配置和自动刷新设置,按以下代码修改:

using System.Diagnostics;
using NLog;

// 初始化NLog监听
var nlogListener = new NLogTraceListener();

// 配置全局Trace
Trace.Listeners.Add(nlogListener);
Trace.Listeners.Remove("Default"); // 移除默认控制台监听,避免重复输出
Trace.AutoFlush = true; // 确保日志立即输出
Trace.WriteLine("Hello world from Trace");

// 配置System.Net的TraceSource(捕获WebClient等网络日志)
var netTraceSource = new TraceSource("System.Net", SourceLevels.All);
netTraceSource.Listeners.Add(nlogListener);
netTraceSource.Listeners.Remove("Default");

// 测试网络日志
var webClient = new WebClient();
try
{
    webClient.DownloadString("http://somehost/nosuchfile.txt");
}
catch { }

3. 优化NLog配置(可选)

你可以针对System.Diagnostics的日志添加专属规则,方便区分来源:

<configuration>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog Log.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          autoReload="true"
          internalLogLevel="Info"
          internalLogFile="nlog-internal.log"> <!-- 开启内部日志排查问题 -->
        <extensions>
            <add assembly="NLog.Targets.ElasticSearch"/>
        </extensions>
        <targets>
            <!-- 你的目标配置不变,仅调整layout增加日志来源标识 -->
            <target name="console"  layout="${longdate} ${windows-identity} ${logger}: ${message}" />
            <target xsi:type="ElasticSearch" name="elasticsearch"
                   uri="http://elasticsearch.dev.xxx-xxx.cloud/"
                   index="BTR.TestAutomation.Shared.Common"
                   includeAllProperties="True"
                   disableAutomaticProxyDetection="True"
                   requireAuth="True"
                   username="xxx"
                   password="xxx">
            </target>
            <target xsi:type="File" name="file" fileName="C:/execution.log"
            layout="${longdate}|${level:uppercase=true}|${logger}: ${message} ${exception}|${all-event-properties}"
            archiveFileName="${basedir}/logs/log.{#}.txt"
            archiveEvery="Day"
            archiveNumbering="DateAndSequence"
            archiveDateFormat="yyyyMMddHHmm"
            maxArchiveFiles="0"
            concurrentWrites="true"
            networkWrites="true"
            />
        </targets>
        <rules>
            <!-- 匹配所有日志,包括System.Diagnostics的 -->
            <logger name="*" minlevel="Trace" writeTo="console,elasticsearch,file" />
            <!-- 可选:针对Trace来源的日志单独设置 -->
            <logger name="Trace" minlevel="Trace" writeTo="console,elasticsearch,file" />
            <!-- 可选:针对System.Net来源的日志单独设置 -->
            <logger name="System.Net" minlevel="Trace" writeTo="console,elasticsearch,file" />
        </rules>
    </nlog>
</configuration>

4. 排查技巧

如果仍无输出,查看NLog内部日志:

  • 配置internalLogFile后,打开生成的nlog-internal.log,检查是否有接收日志失败、ElasticSearch连接错误等信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:10:19