国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-14 16:28:55
字體:
來源:轉載
供稿:網友

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

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="" />    </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.測試效果:

image

image

這里通過“Custom Trace Listener”來實現了日期文件夾的效果,希望有所幫助!


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 左云县| 婺源县| 柞水县| 汕头市| 厦门市| 云林县| 察雅县| 罗平县| 承德县| 南雄市| 吴旗县| 东阿县| 重庆市| 崇州市| 灵石县| 曲沃县| 平遥县| 蕲春县| 双城市| 汶上县| 密山市| 盐边县| 潮安县| 呼和浩特市| 织金县| 临漳县| 婺源县| 丽水市| 长汀县| 武陟县| 汝阳县| 上饶县| 沈丘县| 丰台区| 札达县| 安远县| 云安县| 新蔡县| 苍南县| 临清市| 郧西县|