火星文 技术研习社

Noname Cat, Keep Thinking
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用 AOP 记录可定制的日志信息

Posted on 2006-09-17 01:17  剑廿三  阅读(606)  评论(0)    收藏  举报

在 Service 层加入标注类 MethodLogAttribute

public class MethodLogAttribute : Attribute
{
    
protected string moduleName;
    
protected string description;

    
public MethodLogAttribute(string moduleName, string description)
    {
        
this.moduleName = moduleName;
        
this.description = description;
    }

    
// getters & setters

}


在 AccountManager 业务方法中使用 Log 标注

[MethodLogAttribute("用户管理""添加用户帐号")]
public void CreateAccount(AccountDTO account)
{
    
// .
}


在 LoggerInterceptor 拦截机中处理异常并实现日志记录,拦截机仅拦截使用了 Log 标注的方法。

private ILogger _logger;

public LoggerInterceptor(ILogger logger)
{
    _logger 
= logger;
}

public object Invoke(IMethodInvocation invocation)
{
    
foreach (Attribute attr in invocation.Method.Attributes)
    {
        
if (attr is MethodLogAttribute)
        {
            
bool success = true;

            MethodLogAttribute logAttr 
= attr as MethodLogAttribute;

            
try
            {
                
object value = invocation.Proceed();

            }
            
catch (BusinessException ex)
            {
                success 
= false;
                _logger.Write ( Result.BUSINESS_FAILURE, logAttr.ModuleName, logAttr.Description, 
                    ex.Message.toString(), DateTime.Now);

            }
            
catch (Exception ex)
            {
                success 
= false;
                _logger.Write ( Result.UNKNOWN_FAILURE, logAttr.ModuleName, logAttr.Description, 
                    ex.Message.toString(), DateTime.Now);
            }
            
if(success)
            {
                _logger.Write ( Result.SUCCESS, logAttr.ModuleName, logAttr.Description, 
                    DateTime.Now);
            }
            
return value;
        }

    }
}


配置切面和切入点声明

<configuration>

    
<facilities>
        
<facility id="aspectsharp">
        
<![CDATA[
        import MyProject.Service in MyProject.Tests 
        import MyProject.Service.Interceptors in MyProject.Tests 
        
        interceptors [ "logger" : LoggerInterceptor ] 

        aspect BusinessMethodLogger for [ assignableFrom(IService) ]  
            include "logger" 

            pointcut method(*) 
                advice("logger") 
            end 
        end 
        
]]>
        
</facility>
    
</facilities>

</configuration>


【以上代码未经测试】