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

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

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}
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="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>

.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; }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();
            }
        }

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

10.测试效果:

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

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

时间: 2024-11-11 09:04:12

[Enterprise Library for .NET Framework 2.0]Custom Trace Listener例子演示的相关文章

[Enterprise Library for .NET Framework 2.0]自定义日志路径或日志文件名称

有时候,日志输出的时候会根据时间来分类,譬如"20140821\trace.log",在Enterprise Library中通过工具配置,只能定义日志文件名称,可以通过代码修改FlatFileTraceListenerData实现或Custom Trace Listener方式, 通过代码修改FlatFileTraceListenerData实现代码如下: public static string GetTraceLogPath(string listenersName) { str

[Enterprise Library for .NET Framework 2.0]缓存使用小计

关键代码: using Microsoft.Practices.EnterpriseLibrary.Caching; using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations; using System; namespace ETLUtilHelpV2 { /// <summary> /// Enterprise Library for .NET Framework 2.0 缓存工具类 /// </summary>

Enterprise Library for .NET Framework 2.0缓存使用实例

Enterprise Library for .NET Framework 2.0 是微软发布的企业库,它支持.NET Framework 2.0.并且由一系列的企业应用程序块来构成.本文即以实例展示了Enterprise Library for .NET Framework 2.0缓存的使用方法,供大家参考. 关键代码如下: using Microsoft.Practices.EnterpriseLibrary.Caching; using Microsoft.Practices.Enterp

在数据库访问项目中使用微软企业库Enterprise Library,实现多种数据库的支持

在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreSQL.IBM DB2.或者国产达梦数据库等等,这些数据库的共同特点是关系型数据库,基本上开发的模型都差不多,不过如果我们基于ADO.NET的基础上进行开发的话,那么各种数据库都有自己不同的数据库操作对象,微软企业库Enterprise Library是基于这些不同数据库的操作做的抽象模型,适合多数据

Microsoft Enterprise Library 6.0 之 Exception 企业库异常处理

对于企业库异常处理,这里做个简单的介绍和笔记. 环境 VS2012, .NET Framework 4.0, Microsoft Enterprise Library 6.0 准备工作 1. 下载Enterprise Library配置编辑工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix. 下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789

Enterprise Library 5.0 学习笔记

最近了解了微软提供的企业开发框架Enterprise Library,目前最新版本是6.0,但是不支持FW3.5,所以就学习了5.0的版本,EL5.0支持FW3.5和4.0,官网下载地址是:https://www.microsoft.com/en-us/download/details.aspx?id=15104,将msi文件解压到特定的文件夹就可以有EL5.0的全部dll类库了,EL5.0的文档下载地址是:http://entlib.codeplex.com/releases/view/431

Enterprise Library 5.0 系列教程

1. Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (初级) 2. Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (高级) 3. Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (初级) 4. Microsoft Enterpr

Enterprise Library 6.0 Semantic Logging Application Block Configuration

使用Enterprise Library 6.0的Logging application 模块,配置步骤如下: 1.Nuget 安装 Enterprise Library Logging模块 命令行:Install-package EnterpriseLibrary.Logging. 2.配置文件: 当前基本都是通过Enterprise Library 配置的,但是很不幸,我的总是安装失败,于是自己baidu了一把,然后进行配置,配置如下: <configSections> <secti

转:Enterprise Library 4.0缓存应用程序块

英文原文:http://msdn.microsoft.com/zh-cn/library/cc511588(en-us).aspx Enterprise Library 缓存应用程序块允许开发人员在应用程序中合并一个局部缓存,它支持内存内的缓存,和可选的可以是数据库存储或独立存储的后端存储.应用程序块可以不做修改 的使用,它提供所有必须的获取.添加和移除缓存数据的功能.可配置的到期和清除策略也是应用程序块的一部分. 在构建企业范围发布的应用程序时,架构和开发人员都要面对许多挑战,缓存可以帮助他们