Enterprise Library 2.0 技巧(4):如何用编程的方法来配置Logging Application Block

在本系列的技巧(1技巧(2中分别介绍了使用外部配置文件,使用数据库记录配置信息两种方法,不知道大家有没有想过不使用任何配置文件,也不使用数据库而直接用编程的方法来实现呢?本文将会展示如何使用编程的方法来配置Logging Application Block。首先我们需要了解一下Logging Application Block中比较重要的几个对象:

1LogFormatter

格式化对象,LogFormatterTextFormatterBinaryFormatter两种,多数情况下我们会使用TextFormatter,它通过一个Template来创建,一个完整的Template格式如下:

Timestamp: {timestamp}{newline}

Message: {message}{newline}

Category: {category}{newline}

Priority: {priority}{newline}

EventId: {eventid}{newline}

Severity: {severity}{newline}

Title:{title}{newline}

Machine: {machine}{newline}

Application Domain: {appDomain}{newline}

Process Id: {processId}{newline}

Process Name: {processName}{newline}

Win32 Thread Id: {win32ThreadId}{newline}

Thread Name: {threadName}{newline}

Extended Properties: {dictionary({key} - {value})}{newline}


这里就不具体解释每一项的含义,大家可以参考有关文档,示例代码:


const string Template = "Timestamp: {timestamp}{newline}" +

                            
"Message: {message}{newline}" +

                            
"Category: {category}{newline}" +

                            
"Machine: {machine}{newline}";

TextFormatter formatter 
= new TextFormatter(Template);

2TraceListener
TraceListener提供了日志记录服务,它指定的是日志将被记录到何处,数据库中或者是文本文件,Enterprise Library提供了7

TraceListenerDatabase TraceListener、Email TraceListener、Flat File TraceListener、Formatter Event Log TraceListener、Msmq TraceListener、System Diagnostics TraceListener、WMI Trace Listener。每一种TraceListener都需要一个LogFormatter来对记录的信息进行格式化,例如创建一个FlatFileTraceListener实例:

const string LogFilePath = @"d:\\share\\messages.log";

FlatFileTraceListener logFileListener 
=

            
new FlatFileTraceListener(LogFilePath,

                                       
"----------",

                                       
"----------",

                                       formatter);

这里的formatter就是在上面创建的TextFormatter对象。

3LogSource

LogSource其实就是TraceListener的集合,Enterprise Library允许针对不同的日志信息记录到不同地方,因此可以在LogSource中加入多个TraceListener

LogSource mainLogSource =

            
new LogSource("MainLogSource", SourceLevels.All);

        mainLogSource.Listeners.Add(logFileListener);

4LogFilter

过滤器,对日志信息进行过滤,Enterprise Library默认提供了三种过滤器,用户也可以定义自己的过滤器,示例代码:

// 创建一个类别过滤器

ICollection
<string> categoryfilters = new List<string>();

categoryfilters.Add(DebugCategory);

CategoryFilter categoryFilter 
= new CategoryFilter("CategoryFilter", categoryfilters, CategoryFilterMode.AllowAllExceptDenied);

 

// 加入类别过滤器到集合中

ICollection
<ILogFilter> filters = new List<ILogFilter>();

了解了这四个对象,其实我们就已经知道了该如何去用编程的方法配置Logging Application Block,下面给出一个简单的例子,先写一个MyLogger静态类:

using System;

using System.Collections.Generic;

using System.Diagnostics;

using Microsoft.Practices.EnterpriseLibrary.Logging;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;

using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;

using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;

public static class MyLogger

{

    
static readonly LogWriter _writer;


    
// 日至记录的类别

    
const string ErrorCategory = "Error";

    
const string DebugCategory = "Debug";


    
// 文本文件的路径

    
const string LogFilePath = @"d:\\share\\messages.log";


    
// 模版

    
const string Template = "Timestamp: {timestamp}{newline}" +

                            
"Message: {message}{newline}" +

                            
"Category: {category}{newline}" +

                            
"Machine: {machine}{newline}";

    
static MyLogger()

    
{

        
// 实例化一个TextFormatter,使用前面定义的模版

        TextFormatter formatter 
= new TextFormatter

            (Template);


        
// 实例化TraceListener,记录到文本文件用FlatFileTraceListener

        FlatFileTraceListener logFileListener 
=

            
new FlatFileTraceListener(LogFilePath,

                                       
"----------",

                                       
"----------",

                                       formatter);


        
// 这里是TraceListener的集合,可以增加多个

        LogSource mainLogSource 
=

            
new LogSource("MainLogSource", SourceLevels.All);

        mainLogSource.Listeners.Add(logFileListener);

        IDictionary
<string, LogSource> traceSources = new Dictionary<string, LogSource>();

        traceSources.Add(ErrorCategory, mainLogSource);

        traceSources.Add(DebugCategory, mainLogSource);

        
// 用来表示不记录日志,这点需要注意一下

        LogSource nonExistantLogSource 
= new LogSource("Empty");


        
// 创建一个类别过滤器

        ICollection
<string> categoryfilters = new List<string>();

        categoryfilters.Add(DebugCategory);

        CategoryFilter categoryFilter 
= new CategoryFilter("CategoryFilter", categoryfilters, CategoryFilterMode.AllowAllExceptDenied);


        
// 加入类别过滤器到集合中

        ICollection
<ILogFilter> filters = new List<ILogFilter>();

        filters.Add(categoryFilter);


        _writer 
= new LogWriter(filters,

                        traceSources,

                        nonExistantLogSource,

                        nonExistantLogSource,

                        mainLogSource,

                        ErrorCategory,

                        
false,

                        
true);

    }


    
/// <summary>

    
/// 记录日志信息到Error,默认类别

    
/// </summary>

    
/// <param name="message">日志信息</param>


    
public static void Write(string message)

    
{

        Write(message, ErrorCategory);

    }


    
/// <summary>

    
/// 记录日志信息到特定类别

    
/// </summary>

    
/// <param name="message">日志信息</param>

    
/// <param name="category">类别</param>


    
public static void Write(string message, string category)

    
{

        LogEntry entry 
= new LogEntry();

 

        entry.Categories.Add(category);

        entry.Message 
= message;

 

        _writer.Write(entry);

    }


}

我们再来写一个简单的测试,注意上面的代码中我们过滤掉了Debug类别的日志信息,这样记录到文本文件中的日志信息应该只有My Error一条:

public partial class _Default : System.Web.UI.Page 

{

    
protected void Page_Load(object sender, EventArgs e)

    
{

        MyLogger.Write(
"My Error");

        MyLogger.Write(
"My Debug""Debug");

    }


}

文本文件中输出的结果为:

----------

Timestamp: 2006-7-8 3:45:05

Message: My Error

Category: Error

Machine: RJ-097

----------

输出的结果与我们设想的一致,使用编程的方法配置Logging Application Block简单的就介绍到这里,你也可以使用这种方法来配置其他的应用程序块。不过使用编程的方法来配置,失去了EL的灵活性,要知道EL的根本思想就是配置驱动,但是如果掌握了这些,也许你能够更好的使用EL,在CodeProject上有人写了一篇《Plug-in Manager for Logging - Configure MSEL2 On the fly》,有兴趣的朋友不妨参考一下。

 

参考:

http://davidhayden.com/blog/dave/archive/2006/02/18/2805.aspx

http://geekswithblogs.net/akraus1/archive/2006/02/16/69784.aspx

posted on 2006-07-08 12:52 TerryLee 阅读(4524) 评论(17)  编辑 收藏 所属分类: Enterprise Library.NET Framework

评论

#1楼  2006-07-08 14:40 阿不      

@TerryLee
老兄,你的学习态度真好啊。还说都不做相关的开发的!   回复  引用  查看    

#2楼 [楼主] 2006-07-08 14:50 TerryLee      

@阿不

呵呵,谢谢

以前做过这方面的开发,最近一直在做BI方面,相比之下,我还是比较喜欢前者,所以也一直没有放弃研究:-)   回复  引用  查看    

#3楼  2006-07-09 16:43 学习中 [未注册用户]

太牛了
佩服!   回复  引用  查看    

#4楼 [楼主] 2006-07-10 08:37 TerryLee      

@学习中

谢谢:-)   回复  引用  查看    

#5楼  2006-07-15 23:27 asdfgh129 [未注册用户]

能告诉一下你的MSN吗?有一些EL的问题求教!   回复  引用  查看    

#6楼 [楼主] 2006-07-16 11:18 TerryLee      

@asdfgh129

对不起,我的MSN不再公开

有问题你可以Email给我:-)   回复  引用  查看    

#7楼  2006-07-24 10:04 建议 [未注册用户]

Terry我想请教你个问题,Enterprise Library中UpdateDataSet(dataSet,tableName,insertCommand,updateCommand,deleteCommand)的作用是将insertCommand,updateCommand,deleteCommand所反映出来的CURD操作更新到DataSet里是吗?还是从DataSet更新到数据库里?   回复  引用  查看    

#8楼  2007-02-22 16:03 IT民工 [未注册用户]

如果是要把错误发到对应的E-mail要怎么做?
  回复  引用  查看    


标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-07-08 13:04 编辑过
 
另存  打印
最新IT新闻:
· 阿里巴巴确立未来十年战略规划 修改自身定位
· 微软高管:Wii用户最终会成为Xbox 360用户
· 遵守YouTube案裁定 谷歌将陷入隐私指控深渊
· iPhone入华在即 中国手机产业生存面临考验
· 阿里巴巴集团再向淘宝注资20亿元
 


导航

公告

  • 网名:TerryLee
  • 本名:李会军
  • 位置:中国北京 Ethos
  • 联系方式:
  • 个人主页

 MVP配置

 版权声明

  • 本站采用创作共用许可 署名,非商业

绿色通道

IT新闻

统计

与我联系

留言簿(311)

我的标签

随笔分类

随笔档案

个人站点

关注项目

好的网站

我的好友

友情博客

搜索

积分与排名

阅读排行榜