1. Open the configuration file
2. Remove the unwanted block and add the log block
3. Add "Custom Trace Listener"
4. Define Attributes
5. Add Definition Class Library "customtracelistenerextensions"
6. Write the code as follows:
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))] Public classCustomfilenametracelistener:customtracelistener { PublicCustomfilenametracelistener ():Base() { } Public Override voidWrite (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 ("Write log failed for reason: {0}", ex. Message)); } }Const stringTOKEN =' {DATE} ';Private stringCreateDirectory (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 ("Failed to create path, reason: {0}", ex. Message)); }return_path; } Public Override voidTraceData (TraceEventCache Eventcache,stringSource, TraceEventType EventType,intIdObjectData) { This. Write (data. ToString ()); } Public Override voidWriteLine (stringMessage) { This. Write (message); }Private Static voidWritelog (stringPathstringmsg) {Try{StreamWriter _SW = file.appendtext (path); _SW. WriteLine (msg); _SW. Flush (); _SW. Close (); }Catch(Exception ex) {Debug.WriteLine (string. Format ("Write log failed for reason: {0}", ex. Message)); } }Private Static BOOLCreateFile (stringPath) {BOOL_result =true;Try{if(! File.exists (Path)) {FileStream _files = file.create (path); _files. Close (); } }Catch(Exception) {_result =false; }return_result; } }}
7. Compile, copy the DLL to the bin directory in the directory where the Microsoft Enterprise Library is located, and then reference:
8. Save the configuration, the configuration file is as follows:
<?xml version="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="Logging application Block"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 & Warnings "> <listeners> <add name="Custom Trace Listener"/> </listeners> </errors> </specialSources> </loggingconfiguration></configu Ration>
9. Test the following:
Static voidMain (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 (); } }
10. Test results:
Here through the "Custom Trace Listener" to achieve the effect of the date folder, I hope to help!