[EnterpriseLibraryfor.NETFramework2.0]CustomTraceListener例子演示

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1.打开配置文件

2.移除不需要的Block,并添加Log Block

3.添加“Custom Trace Listener”

4.定义Attributes

5.添加定义类库“CustomTraceListenerExtensions”

6.编写代码,如下:

usingSystem;usingSystem.Collections.Specialized;usingSystem.Diagnostics;usingSystem.IO;usingMicrosoft.PRactices.EnterpriseLibrary.Common.Configuration;usingMicrosoft.Practices.EnterpriseLibrary.Logging.Configuration;usingMicrosoft.Practices.EnterpriseLibrary.Logging.TraceListeners;namespaceCustomTraceListenerExtensions

{

[ConfigurationElementType(typeof(CustomTraceListenerData))]publicclassCustomFileNameTraceListener : CustomTraceListener

{publicCustomFileNameTraceListener()

:base()

{

}publicoverridevoidWrite(stringmessage)

{try{

StringDictionary _attributes =base.Attributes;string_fileName = _attributes["fileName"];string_filePath = CreateDirectory(_fileName);if(CreateFile(_filePath))

{

WriteLog(_filePath,string.Format(Environment.NewLine + message));

}

}catch(Exception ex)

{

Debug.WriteLine(string.Format("写入日志失败,原因:{0}", ex.Message));

}

}conststringTOKEN ="{DATE}";privatestringCreateDirectory(stringfileName)

{string_path = fileName;try{if(!Path.IsPathRooted(_path))

{

_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _path);

}string_date = DateTime.Now.ToString("yyyyMMdd");

_path = _path.Replace(TOKEN, _date);string_directory = Path.GetDirectoryName(_path);if(_directory.Length != 0 && !Directory.Exists(_directory))

{

Directory.CreateDirectory(_directory);

}

}catch(Exception ex)

{

Debug.WriteLine(string.Format("创建路径失败,原因:{0}", ex.Message));

}return_path;

}publicoverridevoidTraceData(TraceEventCache eventCache,stringsource, TraceEventType eventType,intid,objectdata)

{this.Write(data.ToString());

}publicoverridevoidWriteLine(stringmessage)

{this.Write(message);

}privatestaticvoidWriteLog(stringpath,stringmsg)

{try{

StreamWriter _sw = File.AppendText(path);

_sw.WriteLine(msg);

_sw.Flush();

_sw.Close();

}catch(Exception ex)

{

Debug.WriteLine(string.Format("写入日志失败,原因:{0}", ex.Message));

}

}privatestaticboolCreateFile(stringpath)

{bool_result =true;try{if(!File.Exists(path))

{

FileStream _files = File.Create(path);

_files.Close();

}

}catch(Exception)

{

_result =false;

}return_result;

}

}

}

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp{ background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }7.编译,将DLL复制到“Microsoft Enterprise Library”所在目录的BIN目录内,然后引用:

8.保存配置即可,配置文件如下:

<?xmlversion="1.0"encoding="utf-8"?>

<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"/>

</configSections>

<loggingConfiguration name="LoggingapplicationBlock"tracingEnabled="true"defaultCategory="General"logWarningsWhenNoCategoriesMatch="true">

<listeners>

<add fileName="{DATE}\csTrace.log"listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"traceOutputOptions="None"type="CustomTraceListenerExtensions.CustomFileNameTraceListener, CustomTraceListenerExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"name="Custom Trace Listener"initializeData=""/>

</listeners>

<formatters>

<add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"name="Text Formatter"/>

</formatters>

<categorySources>

<add switchValue="All"name="General">

<listeners>

<add name="Custom Trace Listener"/>

</listeners>

</add>

</categorySources>

<specialSources>

<allEvents switchValue="All"name="All Events"/>

<notProcessed switchValue="All"name="Unprocessed Category"/>

<errors switchValue="All"name="Logging Errors &amp; Warnings">

<listeners>

<add name="Custom Trace Listener"/>

</listeners>

</errors>

</specialSources>

</loggingConfiguration>

</configuration>

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }9. 下面进行测试:staticvoidMain(string[] args)

{try{

Action _wirteLog =delegate()

{for(inti = 0; i < 1000; i++)

{

LogEntry log =newLogEntry();

log.Title = Thread.CurrentThread.Name;

log.Message = DateTime.Now.ToString();

Logger.Write(log);

}

};

Thread _task1 =newThread(newThreadStart(_wirteLog));

_task1.Name ="_task1";

_task1.Start();

Thread _task2 =newThread(newThreadStart(_wirteLog));

_task2.Name ="_task2";

_task2.Start();

}catch(Exception ex)

{

Console.WriteLine(ex.Message);

}finally{

Console.ReadLine();

}

}

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }10.测试效果:

这里通过“Custom Trace Listener”来实现了日期文件夹的效果,希望有所帮助!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航