这是一种使用相当容易设置的企业库的方法。您可以使用活动跟踪来存储全局上下文,使用扩展属性来存储本地上下文。
作为示例,我将使用没有任何包装类的服务定位器来演示该方法。
var traceManager = EnterpriseLibraryContainer.Current.GetInstance<TraceManager>();
using (var tracer1 = traceManager.StartTrace("MyRequestId=" + GetRequestId().ToString()))
using (var tracer2 = traceManager.StartTrace("ClientID=" + clientId))
{
DoSomething();
}
static void DoSomething()
{
var logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
logWriter.Write("doing something", "General");
DoSomethingElse("ABC.txt");
}
static void DoSomethingElse(string fileName)
{
var logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
// Oops need to log
LogEntry logEntry = new LogEntry()
{
Categories = new string[] { "General" },
Message = "requested file not found",
ExtendedProperties = new Dictionary<string, object>() { { "filename", fileName } }
};
logWriter.Write(logEntry);
}
配置如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General"
logWarningsWhenNoCategoriesMatch="false">
<listeners>
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="trace.log" formatter="Text Formatter" traceOutputOptions="LogicalOperationStack" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}
Message: {message}
ActivityID: {activity}
Context: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {localMachine}
App Domain: {localAppDomain}
ProcessId: {localProcessId}
Process Name: {localProcessName}
Thread Name: {threadName}
Win32 ThreadId:{win32ThreadId}
Local Context: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
</configuration>
这将导致如下输出:
----------------------------------------
Timestamp: 1/16/2013 3:50:11 PM
Message: doing something
ActivityID: 5b765d8c-935a-445c-b9fb-bde4db73124f
Context: General, ClientID=123456, MyRequestId=8f2828be-44bf-436c-9e24-9641963db09a
Priority: -1
EventId: 1
Severity: Information
Title:
Machine: MACHINE
App Domain: LoggingTracerNDC.exe
ProcessId: 5320
Process Name: LoggingTracerNDC.exe
Thread Name:
Win32 ThreadId:8472
Local Context:
----------------------------------------
----------------------------------------
Timestamp: 1/16/2013 3:50:11 PM
Message: requested file not found
ActivityID: 5b765d8c-935a-445c-b9fb-bde4db73124f
Context: General, ClientID=123456, MyRequestId=8f2828be-44bf-436c-9e24-9641963db09a
Priority: -1
EventId: 0
Severity: Information
Title:
Machine: MACHINE
App Domain: LoggingTracerNDC.exe
ProcessId: 5320
Process Name: LoggingTracerNDC.exe
Thread Name:
Win32 ThreadId:8472
Local Context: filename - ABC.txt
----------------------------------------
注意事项:
- 由于我们正在使用跟踪,因此我们免费获得了可用于关联活动的 .NET 活动 ID。当然,我们也可以使用我们自己的上下文信息(自定义请求 ID、客户端 ID 等)。
- 企业库使用跟踪“操作名称”作为类别,因此我们需要设置 logWarningsWhenNoCategoriesMatch="false" 否则我们会收到一连串的警告消息。
- 这种方法的缺点可能是性能(但我没有测量它)。
如果你想禁用全局上下文(在这个实现中,跟踪)那么你需要做的就是编辑配置文件并设置tracingEnabled="false"。
这似乎是使用内置企业库功能实现目标的一种相当直接的方式。
其他要考虑的方法是可能使用某种非常优雅的拦截(自定义 LogCallHandler)(但这可能取决于现有设计)。
如果您要使用自定义实现来收集和管理上下文,那么您可以考虑使用Trace.CorrelationManager来处理每个线程上下文。您还可以查看创建一个IExtraInformationProvider
以填充扩展属性字典(有关示例,请参见 Enterprise Library 3.1 Logging Formatter Template - Include URL Request)。