技术开发 频道

Enterprise Library:用编程的方法来配置Logging Ap

【IT168技术文档】

    本文将会展示如何使用编程的方法来配置Logging Application Block。首先我们需要了解一下Logging Application Block中比较重要的几个对象:

    1.LogFormatter

    格式化对象,LogFormatter有TextFormatter和BinaryFormatter两种,多数情况下我们会使用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);

    2.TraceListener

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

    TraceListener:Database 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对象。

    3.LogSource

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

LogSource mainLogSource = new LogSource("MainLogSource", SourceLevels.All); mainLogSource.Listeners.Add(logFileListener);
0
相关文章