首页 > 代码库 > [Enterprise Library for .NET Framework 2.0]Custom Trace Listener例子演示
[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; } }}<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目录内,然后引用:
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}
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=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 & 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.测试效果:
这里通过“Custom Trace Listener”来实现了日期文件夹的效果,希望有所帮助!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。