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}
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"/>
</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 & 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”来实现了日期文件夹的效果,希望有所帮助!