我没有尝试使用,<filter>
但最近设置了类似的东西,并且通过使用<switches>
and<sources>
元素成功了。我是这样做的:
<system.diagnostics>
<trace autoflush="true" indentsize="2" />
<sources>
<source name="SyncService" switchName="infoactivity">
<listeners>
<clear />
<add name="file" />
</listeners>
</source>
</sources>
<switches>
<add name="none" value="Off" />
<add name="infoactivity" value="Information, ActivityTracing" />
<...>
</switches>
<sharedListeners>
<add name="file" type="System.Diagnostics.TextWriterTraceListener"
initializeData="sync.log" />
</sharedListeners>
</system.diagnostics>
只需将switchName
值更改为定义的开关之一即可获得适当的日志记录级别。
该代码使用了一个封装在 LogEvent 智能枚举类中的单个静态 TraceSource(我想我曾经在 Jon Skeet 的答案之一中找到了一个示例)。
public class LogEvent {
public static readonly LogEvent SyncStart = new LogEvent(1,
"Sync Service started on {0}", TraceEventType.Start);
public static readonly LogEvent SyncStop = new LogEvent(99,
"Sync Service stopped on {0}", TraceEventType.Stop);
public static readonly LogEvent SyncError = new LogEvent(501,
"\r\n=============\r\n{0}\r\n==============\r\n", TraceEventType.Error);
// etc
private readonly int id;
private readonly string format;
private readonly TraceEventType type;
private static readonly TraceSource trace = new TraceSource("SyncService");
private LogEvent(int id, string format, TraceEventType type)
{
this.id = id;
this.format = format;
this.type = type;
}
public void Log(params object[] data)
{
var message = String.Format(format, data);
trace.TraceEvent(type, id, message);
}
}
在服务代码中,我大量使用了日志语句
LogEvent.SyncStart.Log(DateTime.Now);
LogEvent.SyncError.Log("What the??? -- " + e.Message);
LogEvent.SyncStop.Log(DateTime.Now);