Lab 1: Add Logging to an application 實驗1:給一個應用程序添加日志
In this lab, you will add logging and tracing to an existing application. To begin this exercise, open the EnoughPI.sln file located in the ex01/begin folder. 在這個實驗中,你將添加日志和追蹤到一個已有的程序中。要開始這個練習,請打開在ex01/begin文件夾中的EnoughPI.sln文件。
Note: This exercise involves writing to the event log. The event log trace listener used in this application automatically registers a new event source, but this requires you to run Visual Studio with elevated permissions. Please run Visual Studio as Administrator for this lab.
注意:這個練習包含寫入事件日志。在這個程序中使用的事件日志trace監聽器自動注冊一個新的事件源,但這個要求你用更高的權限運行Visual Studio。在本實驗中請使用管理員身份運行Visual Studio。
To learn about the application 了解這個程序
1.Select the Debug | Start Without Debugging menu command to run the application. 選擇 調試|開始執行(不調試) 菜單命令來運行程序。
The EnoughPI application calculates the digits of pi (π, the ratio of the circumference of a circle to its diameter). Enter your desired PRecision via the NumericUpDown control and click the Calculate button. Be prepared to wait if you want more than 500 digits of precision. EnoughPI程序計算pi的數(π,圓的周長與直徑的比例)。輸入或使用界面上的上下按鈕來確定你想要的精度,然后單擊計算按鈕。如果你想要超過500位的精度,請稍等一段時間。

To add logging to the application 給程序添加日志


Add the following namespace inclusions at the top of the file: 在文件頭部添加下面的命名空間:
using System.Diagnostics;using EnoughPI.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
To configure the application 配置程序
1 private static LoggingConfiguration BuildProgrammaticConfig() 2 { 3 4 // Formatter 5 TextFormatter formatter = new TextFormatter( 6 @"Timestamp:{timestamp(local)}{newline}Message: 7 {message}{newline}Category: {category}{newline}Priority: 8 {priority}{newline}EventId: {eventid}{newline}ActivityId: 9 {property(ActivityId)}{newline}Severity: 10 {severity}{newline}Title:{title}{newline}"); 11 12 // Trace Listeners 13 var eventLog = new EventLog("Application", ".", "EnoughPI"); 14 var eventLogTraceListener = new FormattedEventLogTraceListener( 15 eventLog, 16 formatter 17 ); 18 // Build Configuration 19 var config = new LoggingConfiguration(); 20 config.AddLogSource( 21 Category.General, 22 SourceLevels.All, 23 true).AddTraceListener(eventLogTraceListener); 24 return config; 25 }This LoggingConfiguration consists of a collection of LogSources. Each LogSource specifies a name for the source, the SourceLevel of logs to include, and a Boolean indicating whether or not to enable auto-flush. Adding a TraceListener to the LogSource enables that listener to receive logs from the LogSource and write them to the specified destination with the selected format. For this application, the EventLog source name is set to "EnoughPI." This is the name you will see for log entries when they appear in the Windows Event Log. The LoggingConfiguration specifies that these logs will be listed under the "General" category and that all SourceLevels should be logged. Finally, a LogSource is added to the configuration and the EventLogTraceListener you just created is set to listen to that LogSource. LoggingConfiguration 由一個LogSources集合構成,每個LogSource為源指定一個名稱、日志的SourceLevel和一個Boolean指示是否自動刷新。添加一個TraceListener到LogSource中使得監聽器可以接受來自LogSource的的日志并將日志通過選中的格式化方法寫到指定的目的地。在這個程序中,EventLog源的名稱被設定為"EnoughPI"。這是你將在Windows事件日志中看到的條目的名稱。LoggingConfiguration指定了這些日志將被列在"General"級別下,這樣,所有的SourceLevels都將被記錄。最后,一個LogSource被添加到了配置中而你剛剛創建的EventLogTraceListener將被設置來監聽LogSource。
1 static void Main() 2 { 3 Application.ThreadException += 4 new System.Threading.ThreadExceptionEventHandler( 5 Application_ThreadException); 6 Logger.SetLogWriter(new LogWriter(BuildProgrammaticConfig())); 7 Form entryForm = new MainForm(); 8 Application.EnableVisualStyles(); 9 Application.Run(entryForm);10 // shut down the logger to flush all buffers11 Logger.Reset();12 } The Logger façade is a singleton, so setting it in the EntryPoint enables the same Log Writer instance to be used in all other classes in this project that require logging (for example, The Calculator class) without configuring it more than once. Logger是一個單例,所以在入口點設置就能讓在這個項目中的其他需要記錄日志的類(例如Calculator類)中使用相同的日志記錄器實例,而不用每次使用都做配置。
Note: Using the Logger façade is the simplest use of the Logging Application Block, especially when having only one instance of the LogWriter class, which is the most common case. Nevertheless, in applications that use an Inversion of Control (IoC) Container, you might consider registering the instance of LogWriter directly, so that it can be injected in dependent objects as opposed to those dependent objects using the static façade.
注意:使用Logger靜態類是使用日志應用程序塊的最簡單方法,特別是當只用一個LogWriter類的實例是如此,同時也是最常用的方法。然而,在使用控制反轉容器的程序中,你可能要考慮直接注冊LogWriter的實例,這樣它可以被注入到以來的對象來避免以來的對象使用靜態類。
新聞熱點
疑難解答