【企业库6】【日志应用程序块】实验5:创建和使用自定义的日志格式器

8/3/2015来源:C#应用人气:2234

【企业库6】【日志应用程序块】实验5:创建和使用自定义的日志格式器

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. Select the Formatters\xmlFormatter.cs file in the Solution Explorer. Select the View | Code menu command. Add the following namespaces: 在解决方案资源管理器中选择文件Formatters\XmlFormatter.cs,再选择 视图|代码 菜单命令。添加如下命名空间:
    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;  

     

  2. Add the following highlighted code to the XmlFormatter class. 添加下面高亮的代码到XmlFormatter类中。
     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。并且,你将XmlTextWriterFormatting属性设置为"Indented"缩进,使得日志非常容易阅读。

  3. Select Build | Build Solution to compile the complete solution. 选择 生成|生成解决方案 菜单命令来编译整个解决方案。

To use a custom log formatter 使用自定义日志格式器

  1. In the BuildProgrammaticConfig method in EntryPoint.cs add an XmlFormatter. 在EntryPoint.cs文件的BuildProgrammaticConfig方法中添加一个XmlFormatter
     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