【问题标题】:How to log System.Diagnostics.Trace and System.Diagnostics.Debug messages to NLog file?如何将 System.Diagnostics.Trace 和 System.Diagnostics.Debug 消息记录到 NLog 文件?
【发布时间】:2013-10-03 21:01:45
【问题描述】:

我正在支持一个大型的旧应用程序。该代码使用 NLog 以及 Debug.WriteLineTrace.WriteLine。我正在尝试将 Debug.WriteLine 和 Trace.WriteLine 重定向到 Nlog 文件。所以一切都在一个地方。目前,有些在输出窗口中,有些在日志文件中。

I followed this article to use the NLogTraceListener

那篇文章有 System.Net 和 System.Net.Sockets 被分流到日志文件。我试过了,它有效。我看到 System.Net 和 System.Net.Sockets 消息被记录到文件中。 This SO article 描述了相同的内容 - 并且有效。

不起作用的是将我自己的消息从我自己的命名空间和类记录到日志文件中。

System.Diagnostics.Debug.WriteLine("This won't end up in the log file");
System.Diagnostics.Trace.WriteLine("This won't end up in the log file");

我尝试从我的应用程序中将源名称更改为命名空间。没用。我无法让自己的 WriteLines 记录到文件中。它们仍然出现在 Visual Studio 输出窗口中。

例如:

    <system.diagnostics>
        <sources>
            <source name="MyAppNamespace" switchValue="All">
                <listeners>
                    <add name="nlog" />
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add name="nlog" type="NLog.NLogTraceListener, NLog" />
        </sharedListeners>
    </system.diagnostics>

显式 NLog 调用可以很好地记录到日志文件:

NLog.LogManager.GetCurrentClassLogger().Trace("This Works");

【问题讨论】:

    标签: c# nlog


    【解决方案1】:

    您已配置 TraceSource 以记录到 NLog,但您的跟踪语句未使用该 TraceSource。

    试试:

    <system.diagnostics>
        <trace>
          <listeners>
              <add name="nlog" type="NLog.NLogTraceListener, NLog" />
          </listeners>
        </trace>
    </system.diagnostics>
    

    或者使用你配置的 TraceSource,例如:

    TraceSource source = new TraceSource("MyAppNamespace");
    source.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
    

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 2012-05-22
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      相关资源
      最近更新 更多