[转] C#实现自动化Log日志

简介:

qing2005原文地址 C#实现自动化Log日志

在开发项目的时候,我们不免要使用Log记录日志,使用最多的是Log4Net和EntLib Log,在需要记录日志的代码处加入log.Write(日志信息),假设我需要跟踪业务方法,记录方法的传递参数,执行时间,返回数据等;或者我需要查 看方法的调用关系,希望进入方法的时候自动记录参数信息,出方法时记录结果和执行时间信息。这时就是一个典型的AOP运用,Java在AOP方面是很容易 实现的,因为java有类加载器。但是.Net在AOP方面就不怎么容易,严格意义上.Net没有真正的AOP。这话并不代表.Net不能实现AOP,比 如:PostSharp和Enterprise library就能实现。

先介绍一下PostSharp,我们知道.net代码将编译成MSIL(微软中间语言),然后CPU将MSIL的exe文件生成本地CPU的二进制文件格式,PostSharp就是在编译过程中加入IL代码,因而完成AOP功能。
缺点:编译器需要PostSharp组件,维护代码困难,因为IL代码不好识别;
优点:使用方便(PostSharp2是收费版,破解也比较方便,在此不介绍破解)

这里我重点介绍如何使用Enterprise Library实现自动化Log。


1.首先我们需要下载Enterprise Library,最新为5.0版本;


2.新建一个控制台项目,并添加以下程序集
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.ServiceLocation
Microsoft.Practices.Unity
Microsoft.Practices.Unity.Interception


3.添加AutoLogCallHandler类,实现ICallHandler接口
这个类是执行调用目标方法,在调用目标方法前获取方法的参数信息,并用EntLib Log记录日志;
方法结束后,再次记录日志,并统计执行时间和异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using  System; 
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.Unity.InterceptionExtension; 
using  Microsoft.Practices.EnterpriseLibrary.Logging; 
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration; 
using  System.Diagnostics; 
using  System.Reflection; 
   
namespace  AutoLog { 
     public  class  AutoLogCallHandler:ICallHandler { 
   
         private  LogWriter logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(); 
   
         public  AutoLogCallHandler() { } 
   
         public  IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { 
             StringBuilder sb =  null
             ParameterInfo pi =  null
   
             string  methodName = input.MethodBase.Name; 
             logWriter.Write( string .Format( "Enter method "  + methodName)); 
   
   
             if  (input.Arguments !=  null  && input.Arguments.Count > 0) { 
                 sb =  new  StringBuilder(); 
                 for  ( int  i = 0; i < input.Arguments.Count; i++) { 
                     pi = input.Arguments.GetParameterInfo(i); 
                     sb.Append(pi.Name).Append( " : " ).Append(input.Arguments[i]).AppendLine(); 
                
                 logWriter.Write(sb.ToString()); 
             }        
               
   
             Stopwatch sw =  new  Stopwatch(); 
             sw.Start(); 
   
             IMethodReturn result = getNext()(input, getNext); 
             //如果发生异常则,result.Exception != null 
             if  (result.Exception !=  null ) { 
                 logWriter.Write( "Exception:"  + result.Exception.Message); 
                 //必须将异常处理掉,否则无法继续执行 
                 result.Exception =  null
            
   
             sw.Stop(); 
             logWriter.Write( string .Format( "Exit method {0}, use {1}." ,methodName, sw.Elapsed)); 
   
             return  result; 
        
   
         public  int  Order {  get set ; } 
    

 

4.要自动化日志就需要创建一个标记属性,指定方法能自动进行日志
这里就创建AutoLogCallHandlerAttribute标记属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using  System; 
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.Unity.InterceptionExtension; 
using  Microsoft.Practices.EnterpriseLibrary.Logging; 
using  System.Diagnostics; 
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration; 
   
namespace  AutoLog { 
   
     public  class  AutoLogCallHandlerAttribute:HandlerAttribute { 
   
         public  override  ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container) { 
             return  new  AutoLogCallHandler() { Order =  this .Order }; 
        
    

 5.创建实体类
注意:我在Work和ToString方法上方加上了AutoLogCallHandler属性,它是AutoLogCallHandlerAttribute的简写形式。用以指示这两个方法用AutoLogCallHandler的Invoke来处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using  System; 
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.Unity; 
   
namespace  AutoLog { 
   
     public  class  Employee : MarshalByRefObject  
    
           
         public  Employee() {} 
   
         public  string  Name {  get set ; } 
   
         [AutoLogCallHandler()] 
         public  void  Work() { 
             Console.WriteLine( "Now is {0},{1} is working hard!" ,DateTime.Now.ToShortTimeString(),Name); 
             throw  new  Exception( "Customer Exception" ); 
        
   
         [AutoLogCallHandler()] 
         public  override  string  ToString() { 
             return  string .Format( "I'm {0}." ,Name); 
        
    

 6.测试代码
注意:必须使用PolicyInjection.Create<Employee>()来创建对象,不然无法实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using  System; 
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.EnterpriseLibrary.PolicyInjection; 
using  Microsoft.Practices.Unity; 
using  Microsoft.Practices.EnterpriseLibrary.Logging; 
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration; 
   
namespace  AutoLog { 
     class  Program { 
   
         private  static  LogWriter logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(); 
   
         static  void  Main( string [] args) { 
   
   
             Employee emp = PolicyInjection.Create<Employee>(); 
   
             emp.Name =  "Lele"
   
             emp.Work(); 
             Console.WriteLine(emp); 
        
    

 7.还需要用EntLib的配置工具完成Log配置,将Log信息写入Trace.log文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<? xml  version="1.0"?> 
< configuration
     < configSections
         < section  name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" /> 
     </ configSections
     < loggingConfiguration  name="" tracingEnabled="true" defaultCategory="General"> 
         < listeners
             < add  name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
                 listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
                 fileName="trace.log" formatter="Text Formatter" /> 
         </ listeners
         < formatters
             < add  type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
                 template="Timestamp: {timestamp}{newline} 
Message: {message}{newline} 
Category: {category}{newline} 
Priority: {priority}{newline} 
EventId: {eventid}{newline} 
Severity: {severity}{newline} 
Title:{title}{newline} 
Machine: {localMachine}{newline} 
App Domain: {localAppDomain}{newline} 
ProcessId: {localProcessId}{newline} 
Process Name: {localProcessName}{newline} 
Thread Name: {threadName}{newline} 
Win32 ThreadId:{win32ThreadId}{newline} 
Extended Properties: {dictionary({key} - {value}{newline})}" 
                 name="Text Formatter" /> 
         </ formatters
         < categorySources
             < add  switchValue="All" name="General"> 
                 < listeners
                     < add  name="Flat File Trace Listener" /> 
                 </ listeners
             </ add
         </ categorySources
         < specialSources
             < allEvents  switchValue="All" name="All Events" /> 
             < notProcessed  switchValue="All" name="Unprocessed Category" /> 
             < errors  switchValue="All" name="Logging Errors & Warnings"> 
                 < listeners
                     < add  name="Flat File Trace Listener" /> 
                 </ listeners
             </ errors
         </ specialSources
     </ loggingConfiguration
     < startup
         < supportedRuntime  version="v4.0" sku=".NETFramework,Version=v4.0"/> 
     </ startup
</ configuration

 

好了,测试一下,控制台输入:
Now is 14:03,Lele is working hard!
I'm Lele.
再看看Trace.log文件内容:

  View Code

实现了自动化Log后,回过头来再看第5步,Employee继承了MarshalByRefObject,一般我们的业务类或数据访问类都有基类,那么我们就需要使用接口
这里我添加一个IEmployee接口,里面就Work方法(ToString是重写Object的)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.Unity; 
   
namespace  AutoLog { 
   
     public  interface  IEmployee { 
         void  Work(); 
    
   
     public  class  Employee : IEmployee  
    
           
         public  Employee() { 
             //this.Name = "Lele"; 
        
   
         public  string  Name {  get set ; } 
   
         [AutoLogCallHandler()] 
         public  void  Work() { 
             Console.WriteLine( "Now is {0},{1} is working hard!" ,DateTime.Now.ToShortTimeString(),Name); 
             throw  new  Exception( "Customer Exception" ); 
        
   
         [AutoLogCallHandler()] 
         public  override  string  ToString() { 
             return  string .Format( "I'm {0}." ,Name); 
        
    

 然后在测试类改动一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using  System; 
using  System.Collections.Generic; 
using  System.Linq; 
using  System.Text; 
using  Microsoft.Practices.EnterpriseLibrary.PolicyInjection; 
using  Microsoft.Practices.Unity; 
using  Microsoft.Practices.EnterpriseLibrary.Logging; 
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration; 
   
namespace  AutoLog { 
     class  Program { 
   
         private  static  LogWriter logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(); 
   
         static  void  Main( string [] args) { 
   
             IEmployee emp = PolicyInjection.Create<Employee, IEmployee>(); 
   
             emp.Work(); 
             Console.WriteLine(emp); 
        
    

 

没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。




    本文转自wenglabs博客园博客,原文链接:http://www.cnblogs.com/arxive/p/5848246.html,如需转载请自行联系原作者


相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
24天前
|
Java
使用Java代码打印log日志
使用Java代码打印log日志
77 1
|
25天前
|
Linux Shell
Linux手动清理Linux脚本日志定时清理日志和log文件执行表达式
Linux手动清理Linux脚本日志定时清理日志和log文件执行表达式
78 1
|
29天前
|
SQL 关系型数据库 MySQL
MySQL数据库,可以使用二进制日志(binary log)进行时间点恢复
对于MySQL数据库,可以使用二进制日志(binary log)进行时间点恢复。二进制日志是MySQL中记录所有数据库更改操作的日志文件。要进行时间点恢复,您需要执行以下步骤: 1. 确保MySQL配置文件中启用了二进制日志功能。在配置文件(通常是my.cnf或my.ini)中找到以下行,并确保没有被注释掉: Copy code log_bin = /path/to/binary/log/file 2. 在需要进行恢复的时间点之前创建一个数据库备份。这将作为恢复的基准。 3. 找到您要恢复到的时间点的二进制日志文件和位置。可以通过执行以下命令来查看当前的二进制日志文件和位
|
3天前
|
Java
log4j异常日志过滤规则配置
log4j异常日志过滤规则配置
13 0
|
16天前
|
运维 安全 Ubuntu
`/var/log/syslog` 和 `/var/log/messages` 日志详解
`/var/log/syslog` 和 `/var/log/messages` 是Linux系统的日志文件,分别在Debian和Red Hat系发行版中记录系统事件和错误。它们包含时间戳、日志级别、PID及消息内容,由`rsyslog`等守护进程管理。常用命令如`tail`和`grep`用于查看和搜索日志。日志级别从低到高包括`debug`到`emerg`,表示不同严重程度的信息。注意保护日志文件的安全,防止未授权访问,并定期使用`logrotate`进行文件轮转以管理磁盘空间。
24 1
|
16天前
|
网络协议 应用服务中间件 Linux
centos7 Nginx Log日志统计分析 常用命令
centos7 Nginx Log日志统计分析 常用命令
30 2
|
17天前
|
Ubuntu Linux 网络安全
/var/log/auth.log日志详解
`/var/log/auth.log`是Linux(尤其是Debian系如Ubuntu)记录身份验证和授权事件的日志文件,包括登录尝试(成功或失败)、SSH活动、sudo使用和PAM模块的操作。登录失败、SSH连接、sudo命令及其它认证活动都会在此记录。查看此日志通常需root权限,可使用`tail`、`less`或`grep`命令。文件内容可能因发行版和配置而异。例如,`sudo tail /var/log/auth.log`显示最后几行,`sudo grep &quot;failed password&quot; /var/log/auth.log`搜索失败密码尝试。
72 8
|
14天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
30天前
|
Web App开发 Python
在ModelScope中,你可以使用Python的浏览器自动化库
在ModelScope中,你可以使用Python的浏览器自动化库
17 2
|
1月前
|
存储 BI 数据处理
Python自动化 | 解锁高效办公利器,Python助您轻松驾驭Excel!
Python自动化 | 解锁高效办公利器,Python助您轻松驾驭Excel!