Enterprise Library 2.0 Hands On Lab 翻译(4):日志应用程序块(一)

练习1:添加日志记录到应用程序中

该练习将示范如何向已有的应用程序中添加日志和监测(Trace姑且这么翻译吧,不太准确),并通过Enterprise Library Configuration工具来配置TraceListeners

 

第一步

打开EnoughPI.sln项目,默认的安装路径应该为C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Logging\exercises\ex01\begin,并编译。

 

第二步 关于练习应用程序

选择Debug | Start Without Debugging菜单命令并运行应用程序,EnoughPI程序用来计算∏的精度。在NumericUpDown控件中输入你希望的精度并点击Calculate按钮。

 

第三步 添加日志

1.选择EnoughPI项目,选择Project | Add Reference …菜单命令,在打开的对话框中选择Browse,并添加如下程序集。

Microsoft.Practices.EnterpriseLibrary.Logging.dll;

默认的位置应该是C:\Program Files\Microsoft Enterprise Library January 2006\bin

2.在解决方案管理器中选择Calc\Calculator.cs文件,选择View | Code菜单命令,并添加如下命名空间。

using Microsoft.Practices.EnterpriseLibrary.Logging;

3.记录计算完成时的信息在Calculator.cs文件的OnCalculated方法中添加如下代码。

protected void OnCalculated(CalculatedEventArgs args)

{

    
// TODO: Log final result

    LogEntry log 
= new LogEntry();

    log.Message 
= string.Format("Calculated PI to {0} digits", args.Digits);

    log.Categories.Add(Category.General);

    log.Priority 
= Priority.Normal;

 

    Logger.Write(log);

 

    
if (Calculated != null)

        Calculated(
this, args);

}

创建了一个新的日志项LogEntry并设置参数,使用Logger类的静态方法Write()记录到一个或多个TraceListener。注意这里没有使用硬编码而使用常量的CategoryPriority,在EnoughPI.LoggingConstants.cs中作了如下定义:

public struct Priority

{
    
public const int Lowest  = 0;

    
public const int Low     = 1;

    
public const int Normal  = 2;

    
public const int High    = 3;

    
public const int Highest = 4;

}


public struct Category

{

    
public const string General = "General";

    
public const string Trace   = "Trace";

}

4.记录计算过程的信息在OnCalculated方法中添加如下代码。

protected void OnCalculating(CalculatingEventArgs args)

{

    
// TODO: Log progress

    Logger.Write(

        
string.Format("Calculating next 9 digits from {0}", args.StartingAt),

        Category.General,

        Priority.Low

        );

 

    
if (Calculating != null)

        Calculating(
this, args);

 

    
if (args.Cancel == true)

    
{

        
// TODO: Log cancellation

        Logger.Write(
"Calculation cancelled by user!",

            Category.General, Priority.High);

    }


}

注意这里使用Logger类的重载Write方法来快捷的创建了一个日志项LogEntry

5.记录计算过程的异常信息,添加如下代码到OnCalculatorException方法中。

protected void OnCalculatorException(CalculatorExceptionEventArgs args)

{
    
// TODO: Log exception

    
if (!(args.Exception is ConfigurationErrorsException))

    
{

        Logger.Write(args.Exception, Category.General, Priority.High);

    }


    
if (CalculatorException != null)

        CalculatorException(
this, args);

}

注意这里必须测试异常不能是ConfigurationErrorsException,否则你将无法使用日志记录。对于异常信息的处理通常将会创建一个Enterprise Library 异常应用程序块来处理异常,这在后面的练习中将会看到。

 

第四步 使用企业库配置工具

1.使用Enterprise Library配置工具配置应用程序,可以通过开始菜单打开该配置工具,选择所有程序| Microsoft patterns and practices | Enterprise Library | Enterprise Library Configuration,并打开App.config文件。或者直接在Visual Studio中使用该工具打开配置文件。

2.在解决方案管理器中选中App.config文件,在View菜单或者在右键菜单中选择Open With…,将打开OpenWith对话框,单击Add按钮。

3.在Add Program对话框中,设置Program name指向EntLibConfig.exe文件,默认的路径为C:\Program Files\Microsoft Enterprise Library January 2006\bin,设置Friendly nameEnterprise Library Configuration,单击OK按钮。

Visual Studio会把配置文件(App.config)作为一个命令行参数传递给EntLibConfig.exe

4.在Open With对话框中,选中Enterprise Library Configuration并单击OK按钮。

 

第五步 配置应用程序

1.在应用程序上右击并选择New | Logging Application Block

2.默认的日志应用程序块定义了一个名为GeneralCategoryCategories是一组简单的文本标签,你可以提交日志信息到一组这样的CategoryGeneral类别有一个名为Formatted EventLog TraceListenerTraceListener。要添加一个新的Category,在Category Sources上右击,选择New | Category。一个Category可以有多个TraceListener,而一个TraceListener也可以被多个Category所引用。

注意Category其实是日志信息的一种逻辑分类,可以把要记录的日志信息分为界面日志,异常日志,数据访问日志等,至于具体记录到什么位置,则是由TraceListener来决定的。

3.选择Logging Application Block | Trace Listeners | Formatted EventLog TraceListener节点,设置Source属性为EnoughPI

注意该TraceListener将使用Text Formatter来格式化日志信息,并且记录日志信息到Windows Event Log中。

4.选择菜单File | Save All保存应用程序的配置,并关闭Enterprise Library Configuration工具。

 

第六步 运行应用程序

1.选择Debug | Start Without Debugging菜单命令并运行应用程序,在NumericUpDown控件中输入精度并点击Calculate按钮。

2.打开事件查看器。通过开始 | 管理工具 | 时间查看器,查看应用程序记录的日志信息。

3.双击一条日志项查看详细的信息。

4.退出应用程序

 

第七步 添加监测(Tracing

1.我们经常需要监测应用程序在一个时间区的情况,日志应用程序块为我们提供了Tracing的功能。

2.在解决方案管理器中选择Calc\Calculator.cs文件,选择View | Code菜单命令,在方法Calculate中添加如下代码。

public string Calculate(int digits)

{

    StringBuilder pi 
= new StringBuilder("3", digits + 2);

    
string result = null;

    
try

    
{

        
if (digits > 0)

        
{

            
// TODO: Add Tracing around the calculation

            
using (new Tracer(Category.Trace))

            
{

                pi.Append(
".");

                
for (int i = 0; i < digits; i += 9)

                
{

                    CalculatingEventArgs args;

                    args 
= new CalculatingEventArgs(pi.ToString(), i + 1);

                    OnCalculating(args);

                    
// Break out if cancelled

                    
if (args.Cancel == truebreak;

 

                    
// Calculate next 9 digits

                    
int nineDigits = NineDigitsOfPi.StartingAt(i + 1);

                    
int digitCount = Math.Min(digits - i, 9);

                    
string ds = string.Format("{0:D9}", nineDigits);

                    pi.Append(ds.Substring(
0, digitCount));

                }


            }


        }


        result 
= pi.ToString();

        
// Tell the world I've finished!

        OnCalculated(
new CalculatedEventArgs(result));

    }


    
catch (Exception ex)

    
{

        
// Tell the world I've crashed!

        OnCalculatorException(
new CalculatorExceptionEventArgs(ex));

    }


    
return result;

}

3.在解决方案管理器中选择App.config,选择View | Open With…菜单命令,选择Enterprise Library Configuration并单击OK按钮。

4.选择Logging Application Block节点,设置TracingEnabled属性为True

5.添加新的TraceListener,选中Logging Application Block | Trace Listeners节点,并选择Action | New | FlatFile TraceListener菜单命令。

6.设置Formatter属性为Text Formatter


7
.添加新的监测类别。选中Logging Application Block | Category Sources节点,并选择Action | New | Category菜单命令。

8.设置Name属性为TraceSourceLevels属性为ActivityTracing

这里的类别名Trace将会在代码中使用,设置ActivityTracing级别只会在日志项开始和结束的时候记录监测日志信息。

9.右击新的类别Trace,并选择New | Trace Listener Reference,设置ReferencedTraceListener属性为FlatFile TraceListener

10.选择菜单File | Save All保存应用程序的配置,并关闭Enterprise Library Configuration工具。

11.选择Debug | Start Without Debugging菜单命令并运行应用程序,在NumericUpDown控件中输入精度并点击Calculate按钮。

12.现在可以在文件trace.log中看到监测日志信息。

----------------------------------------

Timestamp: 
13/12/2005 6:08:01 AM

Message: Start Trace: Activity 
'8c07ce3b-235b-4a51-bdcc-83a5997c989e' in method 'Calculate' at 71661842482 ticks

Category: Trace

Priority: 
5

EventId: 
1

Severity: Start

Title:TracerEnter

Machine: TAGGERT

Application Domain: EnoughPI.exe

Process Id: 
6016

Process Name: C:\Program Files\Microsoft Enterprise Library\labs\cs\Logging\exercises\ex01\begin\EnoughPI\bin\Debug\EnoughPI.exe

Win32 Thread Id: 
6092

Thread Name: 

Extended Properties: 

----------------------------------------

----------------------------------------

Timestamp: 
13/12/2005 6:08:01 AM

Message: End Trace: Activity 
'8c07ce3b-235b-4a51-bdcc-83a5997c989e' in method 'Calculate' at 71662624219 ticks (elapsed time: 0.218 seconds)

Category: Trace

Priority: 
5

EventId: 
1

Severity: Stop

Title:TracerExit

Machine: TAGGERT

Application Domain: EnoughPI.exe

Process Id: 
6016

Process Name: C:\Program Files\Microsoft Enterprise Library\labs\cs\Logging\exercises\ex01\begin\EnoughPI\bin\Debug\EnoughPI.exe

Win32 Thread Id: 
6092

Thread Name: 

Extended Properties: 

----------------------------------------

13.关闭应用程序和Visual Studio

完成后的解决方案代码如C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Logging\exercises\ex01\end所示。

 

更多Enterprise Library的文章请参考《Enterprise Library系列文章

作者:TerryLee
出处:http://terrylee.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted @ 2006-10-06 15:59 TerryLee 阅读(6694) 评论(16)  编辑 收藏 网摘 所属分类: [10]  模式与实践

  回复  引用    
#1楼 2007-01-23 10:23 | 哈哈[匿名] [未注册用户]
为什么我在asp.net 2.0下采用Formatted EventLog TraceListener 可以记录日志.而采用FlatFile TraceListener 就找不到日志文件呢.默认的日志文件是放在什么目录下的呢?是不是没有记录啊?权限都打开了呀...
  回复  引用  查看    
#2楼 [楼主]2007-01-23 22:49 | TerryLee      
@哈哈[匿名]
应该是在Bin目录下的
  回复  引用  查看    
#3楼 2007-03-27 14:23 | Teddy      
请问:怎样不通过配置文件,在代码中设置FlatFile TraceListener 日志的文件名称?以及怎么修改日志文件的保存路径?
  回复  引用  查看    
#4楼 2007-08-18 11:25 | fanrsh      
创建了一个 EnterpriseLibrary 交流,学习群,想一起研究的朋友加入(8456438)
  回复  引用    
#5楼 2008-05-06 16:24 | jacob [未注册用户]
这样写入“Application”的日志类型是“Information”,如果想将类型改为"Error"或者"Warning",应该怎么设置?
  回复  引用  查看    
#6楼 2008-07-23 21:20 | 悍马奔野      
trace.log 放在什么地方呢??更改路径了,还是没有。
然后建一个trace.log 。打开一看还是没有内容。
具体trace.log 是放在什么地方。。
bin 目录也没有啊。。
  回复  引用  查看    
#7楼 [楼主]2008-07-23 22:22 | TerryLee      
@悍马奔野
你现在用的是Enterprise Library 哪个版本呢?可以查看一下相关的文档,应该实在bin下面或者应用程序根目录下面。

如果确实没有的话,请查看一下相关文件夹的安全设置,可能是没有写入文件的权限。




标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
Google站内搜索

相关文章:

相关链接: