Lab 5: Create and Use a Custom Log Formatter 實驗5:創建和使用自定義的日志格式器

In this lab, you will add a custom log formatter to a logging application. 在這個實驗中,你將會添加一個自定義的日志格式器到日志程序中。
To begin this exercise, open the EnoughPI.sln file located in the ex05/begin folder. 要開始這個練習,請打開ex05/begin文件夾中的EnoughPI.sln文件。
To create a custom log formatter 創建一個自定義日志格式器
1 using Microsoft.PRactices.EnterpriseLibrary.Common.Configuration;2 using Microsoft.Practices.EnterpriseLibrary.Logging;3 using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;4 using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
1 [ConfigurationElementType(typeof(CustomFormatterData))] 2 public class XmlFormatter : LogFormatter 3 { 4 private NameValueCollection Attributes = null; 5 6 public XmlFormatter(NameValueCollection attributes) 7 { 8 this.Attributes = attributes; 9 }10 public XmlFormatter(string prefix, string ns) 11 {12 this.Attributes = new NameValueCollection(); 13 this.Attributes["prefix"] = prefix; 14 this.Attributes["namespace"] = ns; 15 }16 17 public override string Format(LogEntry log) 18 {19 string prefix = this.Attributes["prefix"]; 20 string ns = this.Attributes["namespace"]; 21 22 using (StringWriter s = new StringWriter()) 23 { 24 XmlTextWriter w = new XmlTextWriter(s); 25 w.Formatting = Formatting.Indented; 26 w.Indentation = 2; 27 w.WriteStartDocument(true); 28 w.WriteStartElement(prefix, "logEntry", ns); 29 w.WriteAttributeString("Priority", ns, 30 log.Priority.ToString(CultureInfo.InvariantCulture)); 31 w.WriteElementString("Timestamp", ns, log.TimeStampString); 32 w.WriteElementString("Message", ns, log.Message); 33 w.WriteElementString("EventId", ns, 34 log.EventId.ToString(CultureInfo.InvariantCulture)); 35 w.WriteElementString("Severity", ns, log.Severity.ToString()); 36 w.WriteElementString("Machine", ns, log.MachineName); 37 w.WriteElementString("AppDomain", ns, log.AppDomainName); 38 w.WriteElementString("ProcessId", ns, log.ProcessId); 39 w.WriteElementString("ProcessName", ns, log.ProcessName); 40 w.WriteElementString("Win32ThreadId", ns, log.Win32ThreadId); 41 w.WriteEndElement(); 42 w.WriteEndDocument(); 43 44 return s.ToString(); 45 } 46 } 47 } The log entry will be formatted as XML. The built-in XmlLogFormatter is useful, but not easily human readable. By creating a custom formatter, you ensure that only the information you care about is included and the information is formatted in a way that makes sense for your purposes. This is accomplished by overriding the Format function of the LogFormatter parent class. Here, you include the Priority, Timestamp, Message, Event Id, Severity, Machine, App Domain, Process Id, Process Name, and Thread Id. Also, you set the XmlTextWriter's Formatting attribute to "Indented," making the logs much easier to read. 日志條目將會被格式化成XML類型。內建XmlLogFormatter 是非常有用的,但是不易于人類閱讀。通過建立一個自定義格式化器,你可以允許僅僅你感興趣的被包含并且信息是按照你覺得合理的目標來格式化的。這是通過重載父類LogFormatter的Format方法來完成的。這里,你可以包含 優先級,時間戳,消息,事件ID,重要性,機器名,程序域,進程ID,進程名和線程ID。并且,你將XmlTextWriter的Formatting屬性設置為"Indented"縮進,使得日志非常容易閱讀。

To use a custom log 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: 8 {property(ActivityId)}{newline}Severity: 9 {severity}{newline}Title:{title}{newline}"); 10 var xmlFormatter = new 11 EnoughPI.Logging.Formatters.XmlFormatter("x", "EnoughPI/2.0"); 12 13 // Trace Listeners 14 var eventLog = new EventLog("Application", ".", "EnoughPI"); 15 var eventLogTraceListener = new 16 FormattedEventLogTraceListener(eventLog, formatter); 17 var flatFileTraceListener = new 18 FlatFileTraceListener( 19 @"C:/Temp/trace.log", 20 "----------------------------------------", 21 "----------------------------------------", 22 formatter); 23 var customTraceListener = new 24 EnoughPI.Logging.TraceListeners.ConsoleTraceListener( 25 "------------------------"); 26 27 customTraceListener.Formatter = xmlFormatter; 28 29 // Build Configuration 30 var config = new LoggingConfiguration(); 31 config.AddLogSource(Category.General, SourceLevels.All, 32 true).AddTraceListener(eventLogTraceListener); 33 config.AddLogSource(Category.Trace, 34 SourceLevels.ActivityTracing, 35 true).AddTraceListener(flatFileTraceListener); 36 37 38 config.LogSources[Category.General].AddTraceListener(customTraceListener); 39 config.IsTracingEnabled = true; 40 return config; 41 } The XmlFormatter constructor expects a collection of attributes, specifically a prefix and namespace. Set prefix as "x" and namespace as "EnoughPI/2.0." Set the Custom Trace Listener you created in the previous lab to use this formatter. XmlFormatter的構造函數需要一個屬性集合,特別指定需要一個前綴和命名空間。設置前綴為"x",命名空間為"EnoughPI/2.0"。設置你在上一個實驗中創建的Custom Trace Listener來使用這個格式器。

To view the Formatter output 查看格式器輸出
1.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 as XML in the application's console window. 選擇 調試|開始執行(不調試)菜單命令來運行程序。輸入你期望的精度然后單擊Calculate按鈕。日志條目就會在程序的控制臺窗口中以XML的格式顯示出來了。

To verify that you have completed the exercise correctly, you can use the solution provided in the ex05/end folder. 你可以打開ex05/end文件夾中提供的解決方案來驗證你是否正確的完成了了練習。
More Information 更多信息
For more information about the Logging Applicatio
新聞熱點
疑難解答