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

1.打开配置文件

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

3.添加“Custom Trace Listener”

4.定义Attributes

5.添加定义类库“CustomTraceListenerExtensions”

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;
        }
    }
}

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

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="" />
    </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>
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();
            }
        }

10.测试效果:

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

[Enterprise Library for .NET Framework 2.0]Custom Trace Listener例子演示,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。