首页 > 代码库 > [Enterprise Library for .NET Framework 2.0]Custom Trace Listener例子演示

[Enterprise Library for .NET Framework 2.0]Custom Trace Listener例子演示

1.打开配置文件

image

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

image

3.添加“Custom Trace Listener”

image

4.定义Attributes

image

5.添加定义类库“CustomTraceListenerExtensions”

image

6.编写代码,如下:

using System;using System.Collections.Specialized;using System.Diagnostics;using System.IO;using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;namespace CustomTraceListenerExtensions{    [ConfigurationElementType(typeof(CustomTraceListenerData))]    public class CustomFileNameTraceListener : CustomTraceListener    {        public CustomFileNameTraceListener()            : base()        {        }        public override void Write(string message)        {            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));            }        }        const string TOKEN = "{DATE}";        private string CreateDirectory(string fileName)        {            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;        }        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)        {            this.Write(data.ToString());        }        public override void WriteLine(string message)        {            this.Write(message);        }        private static void WriteLog(string path, string msg)        {            try            {                StreamWriter _sw = File.AppendText(path);                _sw.WriteLine(msg);                _sw.Flush();                _sw.Close();            }            catch (Exception ex)            {                Debug.WriteLine(string.Format("写入日志失败,原因:{0}", ex.Message));            }        }        private static bool CreateFile(string path)        {            bool _result = true;            try            {                if (!File.Exists(path))                {                    FileStream _files = File.Create(path);                    _files.Close();                }            }            catch (Exception)            {                _result = false;            }            return _result;        }    }}
<style type="text/css">.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; }</style>

7.编译,将DLL复制到“Microsoft Enterprise Library”所在目录的BIN目录内,然后引用:

image

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

<?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=http://www.mamicode.com/"" />    </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=http://www.mamicode.com/"All" name="General">        <listeners>          <add name="Custom Trace Listener" />        </listeners>      </add>    </categorySources>    <specialSources>      <allEvents switchValue=http://www.mamicode.com/"All" name="All Events" />      <notProcessed switchValue=http://www.mamicode.com/"All" name="Unprocessed Category" />      <errors switchValue=http://www.mamicode.com/"All" name="Logging Errors &amp; Warnings">        <listeners>          <add name="Custom Trace Listener" />        </listeners>      </errors>    </specialSources>  </loggingConfiguration></configuration>
<style type="text/css">.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; }</style>9. 下面进行测试:
    static void Main(string[] args)        {            try            {                Action _wirteLog = delegate()                {                    for (int i = 0; i < 1000; i++)                    {                        LogEntry log = new LogEntry();                        log.Title = Thread.CurrentThread.Name;                        log.Message = DateTime.Now.ToString();                        Logger.Write(log);                    }                };                Thread _task1 = new Thread(new ThreadStart(_wirteLog));                _task1.Name = "_task1";                _task1.Start();                Thread _task2 = new Thread(new ThreadStart(_wirteLog));                _task2.Name = "_task2";                _task2.Start();            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);            }            finally            {                Console.ReadLine();            }        }
<style type="text/css">.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; }</style>

10.测试效果:

image

image

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