Logging Application Block 提供了统一的接口用于将日志写入到任何指定的目的地,我们不需要在代码中指定日志信息该写到什么地方,而是在配置文件中设定我们什么情况
下写日志以及将日志信息写到什么地方,这也就意味着操作员可以和我们开发人员一样不通过修改代码来改变日志记录行为。它对于我们程序开发有以下几点好处:
1、可以使我们的应用程序中的日志记录方法保持一致;
2、正是因为它提供一致的结构模型,很大程度上方便了我们开发人员对其的学习;
3、很好的解决了应用程序中的日志问题;
4、可扩展,我们可以自定义日志信息的过滤程序以及格式化日志信息的程序
... ...
相对于上一个版本,Logging Application Block 2.0作出了下列改变:
1、LogEntry对象现在可以属于一个或多个类别(category);
2、2.0版本中我们可以自定义过滤器,在Logging Application Block 将日志信息发送给监听器(trace listeners)之前就将该信息过滤掉,过滤器支持我们根据事件的类别和(或)优先级来过滤事件,我们可以定制符合自己需要的标准的过滤器来过滤事件;
3、你可以在代码中通过查询过滤器来判断当前事件是否需要被记录日志,这样就大大减少了我们日志记录量,可以有效的提高应用程序的性能。
下面我们就来说一下Logging Application Block的使用方法,首先需要添加对下面三个程序集的引用:
using Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
和前面几个Block一样,在使用之前还是先说一下配置方法,首先用配置工具代开我们程序的App.Config/Web.Config,然后选中Application右键,New-->Logging Application Block,如下图:
这时你会发现,在新建的Logging Application Block节点下自动出现了Filters,Category Source,Special Source,Trace Listeners,Formatters这样的几个节点,如下:
我下面按照我配置的顺序来说一下每个节点的作用,首先是Formatters,它用于指定日志信息的格式,如下图,我们在Formatters节点下创建一个Text Formatter,如下:
然后我们可以编辑它的模板,编辑我们要显示的信息,如下:
我们还可以配置Binary Formatter和自定义的Formatter ,这里不在多说了。
Formatter配置好了以后,我们就可以来配置Trace Listeners了,Enterprise Library 2.0 提供了七种Trace Listeners,分别用于将日志信息记录到特定的目的地中,下面我们就来配置一个Flat File Trace Listener ,如下:
使用Flat File Trace Listener后,记录的日志信息就输出到指定的文本文件中,所以我们要指定输出的文本文件的路径,默认在Bin/Debug目录下;同时我们需指定该Listener的Formatter,Name等属性。如果我们配置的是一个DataBase Listener,我们则要在数据库中建立相应的表,并创建一个用于插入日志信息的存储过程。
Trace Listeners 配置好之后就可以开始配置Category Source,我们新建一个Category Source,命名为General,指定其SourceLevel为All,如下:
之后,我们可以对刚添加的Category Source添加一个或多个Trace Listener,本文中,我们将上面配置的SHY52O Formatter加进来,
如上图,在RefrenceTraceListener中选择SHY520 Listeners就可以了。
最后我们来看一下如何配置过滤器(Filters),Enterprise Library 2.0 中提供了三种默认的Filters,分别是:Category Filter ,Log Enable Filter和Priority Filter,我们以Category Filter为例来配置:
然后可以修改过滤器名称和过滤规则:
这里面我们可以选择过滤的模式,过滤模式有两种:
1、Allow All Categories Except those explicitly denied below
2、Deny All Categories Except those explicitly allowed below
根据我们需要选择好过滤模式,然后添加需要过滤的类别,点击OK按钮即可完成Category Filter的配置。
关于Logging Application Block 的介绍和配置部分就说到这里,下一篇我们在来介绍Logging Application Block的使用方法以及自定义Formatter和Listener的方法。
阅读本文之前,请先阅读:Enterprise Library 2.0 -- Logging Application Block (上)
上一篇中我们介绍了如何去配置Logging Application Block,本文将主要介绍Logging Application Block 的基本操作以及Formatter和Trace Listeners 的自定义方法,首先我们来看如何将一个事件日志写入到一个文本文件中。
假设我们按照上一篇的操作配置了Logging Application Block,那么配置文件中的信息如下:
defaultCategory ="General" logWarningsWhenNoCategoriesMatch ="true" >
< listeners >
< add fileName ="trace.log" header ="----------------------------------------"
footer ="----------------------------------------" formatter ="SHY520 Formatter"
listenerDataType ="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions ="None" type ="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="SHY520 Listeners" />
< add source ="Enterprise Library Logging" formatter ="Text Formatter"
log ="Application" machineName ="" listenerDataType ="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions ="None" type ="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="Formatted EventLog TraceListener" />
</ listeners >
< formatters >
< add template ="Timestamp: {timestamp} Message: {message} Category: {category} Priority: {priority} EventId:
{eventid} Severity: {severity} Title:{title} Machine: {machine} Application Domain: {appDomain} Process Id:
{processId} Process Name: {processName} Win32 Thread Id: {win32ThreadId} Thread Name: {threadName} Extended Properties:
{dictionary({key} - {value} )}"
type ="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=null"
name ="Text Formatter" />
< add template ="Timestamp: {timestamp} Message: {message} Category: {category} Priority: {priority} EventId:
{eventid} Severity: {severity} Title:{title} Machine: {machine} Application Domain: {appDomain} Process Id:
{processId} Process Name: {processName} Win32 Thread Id: {win32ThreadId} Thread Name: {threadName} Extended Properties:
{dictionary({key} - {value} )}"
type ="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=null"
name ="SHY520 Formatter" />
</ formatters >
< logFilters >
< add categoryFilterMode ="AllowAllExceptDenied" type ="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="Category Filter" />
</ logFilters >
< categorySources >
< add switchValue ="All" name ="General" >
< listeners >
< add name ="SHY520 Listeners" />
</ listeners >
</ add >
</ categorySources >
< specialSources >
< allEvents switchValue ="All" name ="All Events" />
< notProcessed switchValue ="All" name ="Unprocessed Category" />
< errors switchValue ="All" name ="Logging Errors & Warnings" >
< listeners >
< add name ="Formatted EventLog TraceListener" />
</ listeners >
</ errors >
</ specialSources >
</ loggingConfiguration >
下面我们来看如何将日志写入到文本文件:
public void DoLog()
{
//创建一个日志条目
LogEntry log = new LogEntry();
//指定该日志所属类别
log.Categories.Add("General");
//日志标题
log.Title = "SHY520's Tests";
log.Message = "there is log information";
//优先级
log.Priority = 0;
Logger.Write(log);
}
上面的代码中,我们为该日志指定所属类别为General,在配置文件中我们可以看到General这个类别使用的Trace Listener是SHY520 Listeners,SHY520 Listeners是一个Flat File Trace Listener,它指定了我们的日志信息输出的地方(trace.log),我用的测试项目,运行测试后,该文件在TestResult/out目录中,如果是一般的Web项目或Consle项目,该文件则在Bin/Debug目录下,下面我们来看一下输出的日志信息:
上图中,我们可以看到我们在程序中记录的一些日志信息,我们还可以记录一些额外的信息,这些信息是键值对应的,在1.0版本中我们用Hashtable,这里我们用的是一个泛型的Dictionary类型,代码如下:
public void LoggEntry()
{
LogEntry log = new LogEntry();
//事件ID
log.EventId = 2000;
//日志优先级
log.Priority = 2;
log.Message = "Test LogEntry 2";
//日志类别
ICollection<string> coll = new List<string>();
coll.Add("General");
log.Categories = coll;
//添加额外信息
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("name", "SHY520");
dic.Add("sex","男");
dic.Add("age", "22");
log.ExtendedProperties = dic;
//写入日志
Logger.Write(log);
}
然后运行测试,在TestResult/Out目录下的trace.log文件中就能看到我们在程序中添加的额外信息了。
下面我们来介绍一下过滤器的用法:
实现方法很简单,这里我们假设我们已经按照上一篇文章中的方法配置好了一个Category Filter,在Category Filter中我们可以设置要过滤掉哪种类别的事件日志,具体实现方式有两种,如下:
方法一:
public void TestFilter1()
{
LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("General");
//ShouldLog()方法根据Filter配置返回是否需要记录日志
if (Logger.GetFilter<CategoryFilter>().ShouldLog(logEntry.Categories))
{
//TODO:记录日志
Logger.Write(logEntry);
}
}
方法二:
public void TestFilter2()
{
LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("General");
if (Logger.ShouldLog(logEntry))
{
Logger.Write(logEntry);
}
}
关于事件日志的过滤就说到这里,下面我们来看看如何创建一个自定义的Trace Listener,首先我们新建一个类(MyListener),并且继承与CustomTraceListener,同时不要忘了在为这个新建的类加上[ConfigurationElementType(typeof(CustomTraceListenerData))]的Attribute,最后重写基类的三个方法,在每个方法中加入自己需要的逻辑既可。完整的类的代码如下:
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
namespace Enterprise_Library_2
{
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class MyListener : CustomTraceListener
{
public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id,
object data)
{
if (data is LogEntry && this.Formatter != null)
{
this.WriteLine(this.Formatter.Format(data as LogEntry));
}
else
{
this.WriteLine(data.ToString());
}
}
public override void Write(string message)
{
//TODO:添加自己所需的逻辑
}
public override void WriteLine(string message)
{
//TODO:添加自己所需的逻辑
}
}
}
然后我们在配置Trace Listener的时候选择Custom Trace Listener就可以了。
接下来我们来看看如何自定义Formatter,实现的方法和上面类似,首先新建一个类MyFormatter,继承ILogFormatter接口,同时加上[ConfigurationElementType(typeof(CustomFormatterData))]的Attribute,完整的代码如下:
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
namespace Enterprise_Library_2
{
[ConfigurationElementType(typeof(CustomFormatterData))]
public class MyFormatter : ILogFormatter
{
public MyFormatter(NameValueCollection nv)
{
//注意:构造函数的参数必须是NameValueCollection类型的
}
public string Format(LogEntry log)
{
string result = string.Empty;
//TODO:此处添加我们个性化的Formatter逻辑
return result;
}
}
}
到这里,关于Logging Application Block的有关问题已经都简单的介绍了一下,有遗漏错误的地方,请指正,谢谢!
在前面的文章中,有朋友提到我们在实际项目中往往是把一些事件的日志(比如异常)写入到数据库中,这样更方便查看和管理,而在前面的文章中我都是以写入到文本文件为例的,今天这篇文章就算是对前两篇的一个补充,主要来介绍如何将日志信息写入到数据库中,同时也很感谢那位朋友的建议,下面我们进入正题,分为以下几个步骤:
一、 根据Enterprise Library 2.0中将日志写入到数据库中的需要,我们在数据库中添加一张记录日志的表(RX_Log):
create table RX_Log
(
id int identity not null , -- 流水号
EventId int null , -- 事件ID
Priority int null , -- 优先级
Category varchar ( 1000 ) null , -- 类别
Title varchar ( 500 ) null , -- 日志标题
Message varchar ( 1000 ) null , -- 日志信息
Machine varchar ( 100 ) null , -- 主机名
Timestamps smalldatetime null , -- 记录时间
Severity varchar ( 100 ) null , -- 严重级别
ApplicationDomain varchar ( 1000 ) null , -- 应用程序名
ProcessId int null , -- 进程ID
ProcessName varchar ( 500 ) null , -- 进程名
Win32ThreadId int null , -- 线程ID
ThreadName varchar ( 500 ) null , -- 线程名
ExtendedProperties varchar ( 1000 ) null , -- 扩展信息
primary key (id)
)
Logging Application Block 在写日志到数据库的过程中,还需要两个存储过程(注意:这也是和1.0的一点小区别,上一个版本只需要一个存储过程),分别为:
-- 写日志
create procedure usp_writelogtodatabase
(
@EventId int ,
@Priority int ,
@Title varchar ( 500 ),
@Message varchar ( 4000 ),
@machineName varchar ( 100 ),
@Timestamp smalldatetime ,
@Severity varchar ( 100 ),
@AppDomainName varchar ( 1000 ),
@ProcessId int ,
@ProcessName varchar ( 500 ),
@Win32ThreadId int ,
@ThreadName varchar ( 500 ),
@formattedmessage varchar ( 4000 ),
@LogId int out
)
as
begin
insert into RX_Log
(
EventId,
Priority,
Title,
Message,
Machine,
Timestamps,
Severity,
ApplicationDomain,
ProcessId,
ProcessName,
Win32ThreadId,
ThreadName,
ExtendedProperties
)
values
(
@EventId ,
@Priority ,
@Title ,
@Message ,
@machineName ,
@Timestamp ,
@Severity ,
@AppDomainName ,
@ProcessId ,
@ProcessName ,
@Win32ThreadId ,
@ThreadName ,
@formattedmessage
)
set @LogId = @@identity
end
-- 设置日志类别
create procedure usp_addcategory
(
@categoryName varchar ( 1000 ),
@logID int
)
as
begin
UPDATE RX_Log SET Category = @categoryName WHERE ID = @logID
end
上面的工作做好之后,我们在来配置我们的配置文件,首先我们需要添加一个DataBase的Trace Listener,如下图:
然后指定一些该Trace Listener的属性,包括AddCategoryStoreProcedure,DataBaseInstance,Formatter,Name,TraceOutputOptions以及WriteLogStoreProcedure。
其中AddCategoryStoredProcedure和WriteLogStoredProcedureName就是我们刚刚在数据库中建的存储过程,前者是设置日志类别,后者为向数据库中插入日志的存储过程。DataBaseInstance是我们在Data Access Application Block中建立的一个数据库实例,具体方法可以参考:
Enterprise Library 2.0 -- Data Access Application Block,Formatter则是我们选择上篇文章中设置的SHY520 Formatter,具体的配置方法请参考:
Enterprise Library 2.0 -- Logging Application Block (上)
Enterprise Library 2.0 -- Logging Application Block (下)
其他选项我们先保持默认,接着我们需要添加一个Category,命名为DataBase
然后为这个Category添加一个Trace Listener,并设置其RefrencedTraceListener为我们刚刚建的Database Trace Listener,
这样就完成了我们的配置工作,此时你的配置文件中(Web.Config或App.Config)应该会包含下面的信息:
< configuration >
< configSections >
< section name ="loggingConfiguration" type ="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
< section name ="dataConfiguration" type ="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
</ configSections >
< loggingConfiguration name ="Logging Application Block" tracingEnabled ="true"
defaultCategory ="General" logWarningsWhenNoCategoriesMatch ="true" >
< listeners >
< add databaseInstanceName ="Connection String" writeLogStoredProcName ="usp_writelogtodatabase"
addCategoryStoredProcName ="usp_addcategory" formatter ="SHY520 Formatter"
listenerDataType ="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions ="None" type ="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="Database Trace Listener" />
</ listeners >
< formatters >
< add template ="Timestamp: {timestamp} Message: {message} Category: {category} Priority: {priority} EventId: {eventid} Severity: {severity} Title:{title} Machine: {machine} Application Domain: {appDomain} Process Id: {processId} Process Name: {processName} Win32 Thread Id: {win32ThreadId} Thread Name: {threadName} Extended Properties: {dictionary({key} - {value} )}"
type ="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="SHY520 Formatter" />
</ formatters >
< logFilters >
< add categoryFilterMode ="AllowAllExceptDenied" type ="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name ="Category Filter" />
</ logFilters >
< categorySources >
< add switchValue ="All" name ="DataBase" >
< listeners >
< add name ="Database Trace Listener" />
</ listeners >
</ add >
< add switchValue ="All" name ="General" >
< listeners >
< add name ="SHY520 Listeners" />
</ listeners >
</ add >
</ categorySources >
< specialSources >
< allEvents switchValue ="All" name ="All Events" />
< notProcessed switchValue ="All" name ="Unprocessed Category" />
< errors switchValue ="All" name ="Logging Errors & Warnings" >
< listeners >
< add name ="Formatted EventLog TraceListener" />
</ listeners >
</ errors >
</ specialSources >
</ loggingConfiguration >
< dataConfiguration defaultDatabase ="Connection String" />
< connectionStrings >
< add name ="Connection String" connectionString ="Database=EnterpriseLibrary;Server=shy;Integrated Security=SSPI;uid=sa;pwd=;"
providerName ="System.Data.SqlClient" />
</ connectionStrings >
</ configuration >
上面的工作做完之后,我们就可以在应用程序中添加代码,用于将日志写入数据库了,如下:
public void LogToDataBase()
{
LogEntry log = new LogEntry();
//事件ID
log.EventId = 2000;
//日志优先级
log.Priority = 2;
log.Message = "Test Log Information To DataBase";
//日志类别
ICollection<string> coll = new List<string>();
//设置类别为DataBase,这就确定了你的日志是写入到数据库的
//因为DataBase这个类别中包含一个DataBase Trace Listener
coll.Add("DataBase");
log.Categories = coll;
//添加额外信息
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("name", "SHY520");
dic.Add("sex","男");
dic.Add("age", "22");
log.ExtendedProperties = dic;
//写入日志
Logger.Write(log);
}
运行这个测试方法,然后到数据库中看一下,此时上面的一条日志信息已经写入到数据库中了,关于利用Logging Application Block写日志到数据库中的方法就说到这里,如有遗漏,错误的地方,欢迎您指正!