• 【企业库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 ex05egin folder. 要开始这个练习,请打开ex05egin文件夹中的EnoughPI.sln文件。

    To create a custom log formatter 创建一个自定义日志格式器

    1. Select the FormattersXmlFormatter.cs file in the Solution Explorer. Select the View | Code menu command. Add the following namespaces: 在解决方案资源管理器中选择文件FormattersXmlFormatter.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	race.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 ex05end folder. 你可以打开ex05end文件夹中提供的解决方案来验证你是否正确的完成了了练习。

    More Information 更多信息

    For more information about the Logging Application Block, see the documentation in the EnterpriseLibrary 6 Developer's Guideand the Enterprise Library 6 Reference documentation. 关于日志应用程序块的更多信息,参见企业库6开发者指南中的文档和企业库6参考文档

    Copyright 版权

    This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it. 本文档由"as-is"提供。文档中表达的信息和观点,包括使用的URL和其他因特网网站参考,都可能在没有通知的情况下被更改。自行承担使用本文档可能产生的风险。

    Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred. 这里描述的一些例子仅用于举例说明,并且是虚构的。没有任何故意安排的关联和联系,或推测。

    This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. You may modify this document for your internal, reference purposes © 2013 Microsoft. All rights reserved. 本文不给你提供任何关于微软任意产品的知识产权的合法权利。你可以在你的内部文档或参考文献中复制和使用这个文档。你可以修改该文档作为你的内部参考使用。

    Microsoft, MSDN, Visual Studio, and Windows are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.

  • 相关阅读:
    JavaScript学习-自定义对象/
    网站特效:欢迎窗口/发表评论
    javacript中的事件
    DOM / DOM操作表格
    如何设置文本不换行省略号显示等CSS常用文本属性
    从零开始的H5生活
    Spring手动提交事务
    java基础学习之接口
    java基础学习之抽象类
    java基础学习之final关键字
  • 原文地址:https://www.cnblogs.com/Arnu/p/loggingblock5.html
Copyright © 2020-2023  润新知