简体   繁体   English

如何将 System.Diagnostics.Trace 和 System.Diagnostics.Debug 消息记录到 NLog 文件?

[英]How to log System.Diagnostics.Trace and System.Diagnostics.Debug messages to NLog file?

I'm supporting a large, old application.我正在支持一个大型的旧应用程序。 The code uses NLog as well as Debug.WriteLine and Trace.WriteLine .该代码使用 NLog 以及Debug.WriteLineTrace.WriteLine I'm trying to redirect the Debug.WriteLine and the Trace.WriteLine to the Nlog file.我正在尝试将 Debug.WriteLine 和 Trace.WriteLine 重定向到 Nlog 文件。 So that everything is in one place.所以一切都集中在一个地方。 At the moment, some is in the Output window and some is in the log file.目前,有些在输出窗口中,有些在日志文件中。

I followed this article to use the NLogTraceListener 我按照这篇文章使用 NLogTraceListener

That article has System.Net and System.Net.Sockets getting shunted to the log file.那篇文章将 System.Net 和 System.Net.Sockets 分流到日志文件。 I tried it and it works.我试过了,它有效。 I see System.Net and System.Net.Sockets messages getting logged to the file.我看到 System.Net 和 System.Net.Sockets 消息被记录到文件中。 This SO article describes the same -- and it works. 这篇 SO 文章描述了相同的内容 - 并且它有效。

What doesn't work is logging my own messages from my own namespaces and classes to the log file.不起作用的是将我自己的消息从我自己的命名空间和类记录到日志文件中。

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");

I've tried changing the source names to namespaces from my app.我尝试将源名称从我的应用程序更改为命名空间。 Didn't work.没用。 I cannot get my own WriteLines to log to the file.我无法让自己的 WriteLines 登录到文件。 They still appear in the Visual Studio output window.它们仍然出现在 Visual Studio 输出窗口中。

For instance:例如:

    <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>

The explicit NLog calls are logging to the log file just fine:显式 NLog 调用记录到日志文件就好了:

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

You've configured a TraceSource to log to NLog, but your trace statement isn't using that TraceSource.您已将TraceSource配置为记录到 NLog,但您的跟踪语句未使用该 TraceSource。

Try:尝试:

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

Or use the TraceSource you've configured, for example:或者使用您配置的 TraceSource,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM