创建和使用自定义的日志格式器
2014-02-14 00:54
801 查看
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 创建一个自定义日志格式器
Select the Formatters\XmlFormatter.cs file in the Solution Explorer. Select the
View | Code menu command. Add the following namespaces: 在解决方案资源管理器中选择文件Formatters\XmlFormatter.cs,再选择 视图|代码 菜单命令。添加如下命名空间:
Add the following highlighted code to the
XmlFormatter class. 添加下面高亮的代码到XmlFormatter类中。
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"缩进,使得日志非常容易阅读。
Select Build | Build Solution to compile the complete solution. 选择 生成|生成解决方案 菜单命令来编译整个解决方案。
To use a custom log formatter 使用自定义日志格式器
In the BuildProgrammaticConfig method in
EntryPoint.cs add an XmlFormatter. 在EntryPoint.cs文件的BuildProgrammaticConfig方法中添加一个XmlFormatter
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 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.
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 创建一个自定义日志格式器
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;
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。并且,你将XmlTextWriter的Formatting属性设置为"Indented"缩进,使得日志非常容易阅读。
Select Build | Build Solution to compile the complete solution. 选择 生成|生成解决方案 菜单命令来编译整个解决方案。
To use a custom log formatter 使用自定义日志格式器
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 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.
相关文章推荐
- 使用logback输出日志,自定义输出格式
- [转]使用NLog记录日志到数据库 自定义日志表的数据格式
- delphi 10.2 创建并使用资源文件(一共22种格式,RCDATA是自定义格式)
- (Unity)Unity自定义Debug日志文件,利用VS生成Dll文件并使用Dotfuscated进展混淆,避免被反编译
- C#如何创建自定义控件以及添加自定义属性和事件使用
- 使用chukwa的自定义数据类型收集日志配置问题
- Azure运维系列 6:使用自定义映像创建虚拟机
- 【REACT NATIVE 系列教程之二】创建自定义组件&&导入与使用示例
- ASP.NET - 使用 Microsoft AJAX Library 创建自定义客户端脚本
- 创建、配置和使用自定义JSP标签
- 使用XAML创建自定义图形
- poi-12创建用户自定义数据格式
- 使用 Professional PowerToy TimerShot 为WindowsXPEmbedded创建自定义组件
- 使用AngularJS创建自定义的过滤器的方法
- 【COCOS2DX-LUA 脚本开发之五】Lua 使用OOP(面对对象思想编程),免Binding创建自定义lua类
- Spring关于使用注解@Configuration去配置FormattingConversionServiceFactoryBean来实现自定义格式字符串处理无效的问题(未找到是什么原因造成的)
- Oracle创建序列,序列的语法格式及使用和查询
- 常规功能和模块自定义系统 (cfcmms)—025开发日志(创建iconCls的field)
- 工具类——使用Timber自定义日志并保存文件查看
- 【COCOS2DX-LUA 脚本开发之四】使用tolua++编译pkg,从而创建自定义类让Lua脚本使用