Lab 4: Create and Use a Custom Trace Listener 创建和使用自定义跟踪监听器
In this lab, you will build a custom Trace Listener to send formatted log entries to the Console standard output. You will then add this new Trace Listener to the EnoughPI application and monitor the log entries in real-time. 在这个实验中,你将会创建一个自定义的跟踪监听器来将格式化后的日志条目发送到控制台标准输出。之后你将会添加这个新的跟踪监听器到EnoughPI程序并实时监视日志条目。
To begin this exercise, open the EnoughPI.sln file located in the ex04egin folder. 打开ex04egin文件夹中的EnoughPI.sln文件来开始这个练习。
To create a custom Trace Listener 创建一个自定义跟踪监听器
-
Select the TraceListenersConsoleTraceListener.cs file in the Solution Explorer. Select the View | Code menu command. Add the following namespaces:在解决方案资源管理器中选中 TraceListenersConsoleTraceListener.cs文件,然后选择 视图|代码菜单命令。添加下面的命名空间:
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
-
Add the following highlighted code to the ConsoleTraceListener class. 添加高亮的代码到ConsoleTraceListener类。
1 [ConfigurationElementType(typeof(CustomTraceListenerData))] 2 public class ConsoleTraceListener : CustomTraceListener 3 { 4 public ConsoleTraceListener() 5 : base() 6 { 7 } 8 9 public ConsoleTraceListener(string del) 10 { 11 this.Attributes["delimiter"] = del; 12 } 13 14 public override void TraceData(TraceEventCache eventCache, 15 string source, TraceEventType eventType, int id, object data) 16 { 17 if (data is LogEntry && this.Formatter != null) 18 { 19 this.WriteLine(this.Formatter.Format(data as LogEntry)); 20 } 21 else 22 { 23 this.WriteLine(data.ToString()); 24 } 25 } 26 27 public override void Write(string message) 28 { 29 Console.Write(message); 30 } 31 32 public override void WriteLine(string message) 33 { 34 // Delimit each message 35 Console.WriteLine((string)this.Attributes["delimiter"]); 36 // Write formatted message 37 Console.WriteLine(message); 38 } 39 }
Note: The base class is CustomTraceListener, which mandates that you override two abstract methods: Write(string message) and WriteLine(string message). However, to format the message we need to override the TraceData method.
主意:基类是CustomTraceListener,其要求你重载两个抽象方法:Write(string message) 和 WriteLine(string message)。不过格式化消息我们还需要重载TraceData方法。
The ConsoleTraceListener is expecting a parameter, delimiter, as part of the listener configuration. ConsoleTraceListener类期望一个参数: delimiter,作为监听器配置的一部分。
- Select the Build | Build Solution menu command, to compile the complete solution. 选择 生成|生成解决方案 菜单命令,来编译整个解决方案。
To use a custom Trace Listener 使用自定义的跟踪监听器
-
In EntryPoint.cs add your CustomTraceListener to your logging configuration in the BuildProgrammaticConfig method. 在EntryPoint.cs文件的方法BuildProgrammaticConfig中将你的自定义跟踪监听器添加到你的日志配置信息里。
1 private static LoggingConfiguration BuildProgrammaticConfig() 2 { 3 // Formatter 4 TextFormatter formatter = new TextFormatter(@"Timestamp: 5 {timestamp(local)}{newline}Message: {message}{newline}Category: 6 {category}{newline}Priority: {priority}{newline}EventId: 7 {eventid}{newline}ActivityId: 8 {property(ActivityId)}{newline}Severity: 9 {severity}{newline}Title:{title}{newline}"); 10 11 // Trace Listeners 12 var eventLog = new EventLog("Application", ".", "EnoughPI"); 13 var eventLogTraceListener = new 14 FormattedEventLogTraceListener(eventLog, formatter); 15 var flatFileTraceListener = new 16 FlatFileTraceListener( 17 @"C:Temp race.log", 18 "----------------------------------------", 19 "----------------------------------------", 20 formatter); 21 22 var customTraceListener = 23 new EnoughPI.Logging.TraceListeners.ConsoleTraceListener( 24 "-----------------------"); 25 26 // Build Configuration 27 var config = new LoggingConfiguration(); 28 config.AddLogSource( 29 Category.General, 30 SourceLevels.All, 31 true).AddTraceListener(eventLogTraceListener); 32 config.AddLogSource( 33 Category.Trace, 34 SourceLevels.ActivityTracing, 35 true).AddTraceListener(flatFileTraceListener); 36 37 config.LogSources[Category.General].AddTraceListener( 38 customTraceListener); 39 config.IsTracingEnabled = true; 40 41 return config; 42 }
Because the LogSource named Category.General already exists, you can add another trace listener to it by referencing the LogSource by name, as above. 因为叫做Category.General 的LogSource已经存在,所以你可以通过引用LogSource的名字来添加另一个跟踪监听器到其中,如上面代码所示。
Note: You will remember your ConsoleTraceListener is expecting a parameter named delimiter, which is printed before each formatted log entry is written to the console.
注意:你还记得你的ConsoleTraceListener需要一个名为delimiter的参数,它将在在每个日志条目被输出到控制台之前打印出来。
-
Set the Formatter tothe Text Formatter you created earlier. 设置格式器为你早先创建过的Text Formatter。
1 private static LoggingConfiguration BuildProgrammaticConfig() 2 { 3 // Formatter 4 TextFormatter formatter = new TextFormatter(@"Timestamp: 5 {timestamp(local)}{newline}Message: {message}{newline}Category: 6 {category}{newline}Priority: {priority}{newline}EventId: 7 {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: 8 {severity}{newline}Title:{title}{newline}"); 9 10 // Trace Listeners 11 var eventLog = new EventLog("Application", ".", "EnoughPI"); 12 var eventLogTraceListener = 13 new FormattedEventLogTraceListener(eventLog, formatter); 14 var flatFileTraceListener = 15 new FlatFileTraceListener( 16 @"C:Temp race.log", 17 "----------------------------------------", 18 "----------------------------------------", 19 formatter); 20 var customTraceListener = 21 new EnoughPI.Logging.TraceListeners.ConsoleTraceListener( 22 "----------------------"); 23 customTraceListener.Formatter = formatter; 24 25 // Build Configuration 26 var config = new LoggingConfiguration(); 27 config.AddLogSource( 28 Category.General, 29 SourceLevels.All, 30 true).AddTraceListener(eventLogTraceListener); 31 config.AddLogSource( 32 Category.Trace, 33 SourceLevels.ActivityTracing, 34 true).AddTraceListener(flatFileTraceListener); 35 config.LogSources[Category.General].AddTraceListener( 36 customTraceListener); 37 38 39 config.IsTracingEnabled = true; 40 41 return config; 42 }
To view the Trace Listener output查看跟踪监听器的输出
- Select the EnoughPI project. Select the Project | EnoughPI Properties… menu command, select the Application tab, and set Output type to Console Application. 选中EnoughPI项目,选择 项目|属性菜单命令,选择应用程序标签页,然后设置输出类型为控制台程序。
- Select the File | Save All menu command.选择 文件|保存全部 菜单命令。
- Select the Debug | Start Without Debugging menu command to run the application. Enter your desired precision and click the Calculate button. The log entries will be displayed in the application's console window, as you see here.选择 调试|开始执行(不调试)菜单命令来运行程序。输入你希望的精度并单击Calculate按钮。日志条目就会被显示在程序的控制台窗口里,就像你在这儿看到的一样:
To verify that you have completed the exercise correctly, you can use the solution provided in the ex04end folder. 你可以打开ex04end文件夹中提供的解决方案来验证你是否正确的完成了了练习。