【企业库6】【日志应用程序块】实验1:给应用程序添加日志

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

【企业库6】【日志应用程序块】实验1:给应用程序添加日志

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 给程序添加日志

  1. Select the EnoughPI project. Select the Project | Manage NuGet Packages menu command or right-click on the References in the Solution Explorer. 选择EnoughPI项目。选择 项目|管理NuGet程序包菜单命令或者在解决方案资源管理器中右键引用。
  2. Select the "Online" option to view NuGet packages available online. 选择"联机"选项来查看联机可用的NuGet程序包。

  3. Search for EntLib6 in the search bar. Select Enterprise Library – Logging Application Block and click install. 在搜索栏搜索EntLib6。选择Enterprise Library – Logging Application Block并单击安装。

  4. Click Accept on the License Acceptance window that pops up. 单击在弹出的许可协议窗口中"接受"按钮。
  5. Select the EntryPoint.cs file in Solution Explorer and view it. 在解决方案资源管理器中选择EntryPoint.cs文件。

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. Add the following method to EntryPoint.cs: 添加下列方法到EntryPoint.cs:
       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指示是否自动刷新。添加一个TraceListenerLogSource中使得监听器可以接受来自LogSource的的日志并将日志通过选中的格式化方法写到指定的目的地。在这个程序中,EventLog源的名称被设定为"EnoughPI"。这是你将在Windows事件日志中看到的条目的名称。LoggingConfiguration指定了这些日志将被列在"General"级别下,这样,所有的SourceLevels都将被记录。最后,一个LogSource被添加到了配置中而你刚刚创建的EventLogTraceListener将被设置来监听LogSource。

    2. Change the Logger to use this configuration and to dispose it after the application runs in the Main method: 在Main函数中修改Logger来使用这个配置信息并在程序运行结束之后释放掉他。
       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的实例,这样它可以被注入到以来的对象来避免以来的对象使用静态类。

    3. Open the Calc/Calculator.cs file and add the following using statement. 打开Calc/Calculator.cs文件,然后将下面的引用添加到文件中。