【问题标题】:Automatically log System.diagnostics.trace messages to an Nlog target自动将 System.diagnostics.trace 消息记录到 Nlog 目标
【发布时间】:2012-10-26 23:23:55
【问题描述】:
假设您在整个应用程序中都有 C# 跟踪消息。类似的东西:
Trace.TraceInformation("Service Started");
如何自动将其记录到 nLog 目标,而无需向所有具有跟踪消息的类添加如下代码?
using NLog;
private static Logger logger = LogManager.GetCurrentClassLogger();
有没有办法做到这一点,而不包括 .NET Framework 本身产生的跟踪,this article 演示了如何做到这一点?
【问题讨论】:
标签:
c#
trace
nlog
system.diagnostics
【解决方案1】:
你可以使用NLog的NLogTraceListener。
为了完整起见,这里是用于指定 NLogTraceListener 的 System.Diagnostics 配置(来自上面的链接):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" switchValue="All">
<listeners>
<add name="nlog" />
</listeners>
</source>
<source name="System.Net.Sockets" switchValue="All">
<listeners>
<add name="nlog" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="nlog" type="NLog.NLogTraceListener, NLog" />
</sharedListeners>
</system.diagnostics>
</configuration>
您还需要配置 NLog 以告诉它从 System.Diagnostics.Trace 移动到 NLog 后如何写入信息:
<nlog>
<targets>
<target name="console" type="ColoredConsole" layout="${longdate} ${windows-identity} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console" />
</rules>
</nlog>
【解决方案2】:
这适用于没有明确来源的情况。
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="MyNLogTraceListener" type="NLog.NLogTraceListener, NLog" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
【解决方案3】:
您可以在App.config 中使用以下内容
<system.diagnostics>
<sources>
<source name="System" switchValue="All">
<listeners>
<add name="nlog" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="nlog" type="NLog.NLogTraceListener, NLog" />
</sharedListeners>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="nlog" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>