用annotation处理logging

前段时间,项目中讨论了改进logging的问题。

 

我们在日常的代码中常常需要在在一个方法(method)的开始的时候log一下输入参数,在方法(method)结束时log一下return参数(很常见的问题),之前我们都是通过开发人员自己手动写代码去实现log,但是这样真的很麻烦,很多类似log的代码在程序里也不好看,于是借鉴了他人的想法,利用反射和method级的annotation来实现对入参和return值的logging。

 

1。首先定义一个Annotation来标记method是否需要打log

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodLogEnabler {
    /**
     * log flag
     */
    public static enum LOG {
    /**
     * log input parameters
     */
    IN,
    /**
     * log output parameters
     */
    OUT,
    /**
     * log both input & output parameters
     */
    IN_OUT} 
    
    /**
     * The log value
     * @return The log value
     */
    public LOG value();
}

 

 

2。实现一个写log的Spring拦截器

public class MethodLoggerInterceptor implements MethodInterceptor{

    public Object invoke(MethodInvocation arg0) throws Throwable {
        MethodLoggerHandler handler = new MethodLoggerHandler();
        MyLogger logger = new MyLogger();
        handler.setLogger(logger);
        return handler.execute(arg0);
    }
}

 

    拦截器所调用的handler类

/**
 * To check if the invoking method is registered MethodLogEnabler
 * annotation, and log invoking method's parameter if the annotatioin
 * is registered
 */
public class MethodLoggerHandler {
    /**
     * Default Constructor
     */
    public MethodLoggerHandler(){
        //Default Constructor
    }
    /**
     * 
     * @param methodInvocation
     * @return Object
     * @throws Throwable
     */
    public Object execute(MethodInvocation methodInvocation) throws Throwable {

        Method method = methodInvocation.getMethod();

        MethodLogEnabler annotation = null;
        //Check if annotation exists
        if (method != null && method.getAnnotation(MethodLogEnabler.class) != null) {
            annotation = method.getAnnotation(MethodLogEnabler.class);
        }
        
        //try to log method's input parameter
        if (method != null && annotation != null) {
            logInputParameters(methodInvocation, method, annotation);
        }

        Object result = null;
        try {
            //the original method call
            result = methodInvocation.proceed();
        } catch (Throwable e) {
            //log the error.
            if (logger != null) {
                logger.error("", e);
            }
            throw e;
        }
        
        //try to log method's return values
        if (method != null && annotation != null) {
            logOutputValues(method, annotation, result);
        }
        
        return result;
    }
        
    private void append(Object obj, StringBuilder appender) {
        if (obj != null) {
            //handle array object 
            if (obj.getClass().isArray()) {
                Object[] objects = (Object[]) obj;
                appender.append(getArrayOutput(objects));
            }
            //handle list object
            if (obj instanceof List) {
                Object[] objects = toArray(obj);
                appender.append(getArrayOutput(objects));
            }

            appender.append(obj.toString());
        }
    }
    
    @SuppressWarnings("unchecked")
    private Object[] toArray(Object obj) {
        Object[] objects = ((List) obj).toArray();
        return objects;
    }

    private String getArrayOutput(Object[] objects) {
        if ((objects != null) && (objects.length > 0)) {

            StringBuffer arrayOutput = new StringBuffer();
            arrayOutput.append("ARRAY[");
            for (Object object : objects) {
                if (object != null) {
                    arrayOutput.append(object.toString()).append(",");
                }
            }

            // remove last ,
            if (arrayOutput.length() > 0) {
                arrayOutput.replace(arrayOutput.length() - 1, arrayOutput.length(), "");
            }
            
            arrayOutput.append("]");
            return arrayOutput.toString();
        }
        return null;
    }
    
    private void logOutputValues(Method method, MethodLogEnabler annotation, Object result) {
        if (MethodLogEnabler.LOG.OUT.equals(annotation.value())
                || MethodLogEnabler.LOG.IN_OUT.equals(annotation.value())) {
            
            //the method has return
            if (!Void.TYPE.equals(method.getReturnType())) {
                
                StringBuilder output = new StringBuilder();
                output.append("Class[").append(method.getDeclaringClass().getName()).append("]: Method[")
                        .append(method.getName()).append("]: Retrun Value[");

                append(result, output);

                output.append("]");

                if (logger != null && logger.isDebugEnabled()) {
                    logger.debug(output.toString());
                }
            }
        }
    }
    
    private void logInputParameters(MethodInvocation methodInvocation, Method method, MethodLogEnabler annotation) {
        if (MethodLogEnabler.LOG.IN.equals(annotation.value())
                || MethodLogEnabler.LOG.IN_OUT.equals(annotation.value())) {
            
            //the method has input parameters
            if (method.getParameterTypes().length > 0) {
                
                StringBuilder string = new StringBuilder();
                string.append("Class[").append(method.getDeclaringClass().getName()).append("]: Method[").append(
                        method.getName()).append("]: Parameter[");
                
                for (Object input : methodInvocation.getArguments()) {
                    if (logger != null && logger.isDebugEnabled()) {
                        append(input, string);
                        string.append(",");
                    }
                }
                string.append("]");

                if (logger != null && logger.isDebugEnabled()) {
                    logger.debug(string.toString());
                }
            }
        }
    }
    /**
     * @param logger The logger to set.
     */
    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    /**
     * @return Returns the logger.
     */
    public Logger getLogger() {
        return logger;
    }

    private Logger logger;
}

 

3。Junit的测试

写一个DumpDTO

/**
 * class DumpDTO
 */
public class DumpDTO {
    private String id;
    private int num;
    private Date time;
    private Long u;
    
    
    /**
     * @return Returns the id.
     */
    public String getId() {
        return id;
    }
    /**
     * @param id The id to set.
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return Returns the num.
     */
    public int getNum() {
        return num;
    }
    /**
     * @param num The num to set.
     */
    public void setNum(int num) {
        this.num = num;
    }
    /**
     * @return Returns the time.
     */
    public Date getTime() {
        return time;
    }
    /**
     * @param time The time to set.
     */
    public void setTime(Date time) {
        this.time = time;
    }
    /**
     * @return Returns the u.
     */
    public Long getU() {
        return u;
    }
    /**
     * @param u The u to set.
     */
    public void setU(Long u) {
        this.u = u;
    }

}

 

建一个DumpHandler接口,接口里使用刚创建的MethodLogEnabler标签去定义哪些方法需要打log

public interface DumpHandler {
    /**
     * no log, because no input paramters
     */
    @MethodLogEnabler(MethodLogEnabler.LOG.IN)
    public void doA();
    /**
     * 
     * @param a
     * @param b
     * @param c
     * @param d
     */
    @MethodLogEnabler(MethodLogEnabler.LOG.IN)
    public void doB(String a, int b, Date c, Long d);
    /**
     * Only log return values
     * @param dto
     * @param string
     * @return DumpDTO
     */
    @MethodLogEnabler(MethodLogEnabler.LOG.OUT)
    public DumpDTO doC(DumpDTO dto, String string);
    /**
     * Log both input parameters and return values
     * @param dto
     * @return List<DumpDTO>
     */
    @MethodLogEnabler(MethodLogEnabler.LOG.IN_OUT)
    public List<DumpDTO> doD(DumpDTO[] dto);
}

 简单的实现Handler的接口

public class DumpHandlerImpl implements DumpHandler {

    /* (non-Javadoc)
     * @see se.ericsson.nrg.ws.adapter.bwlist.DumpHandler#doA()
     */
    public void doA() {
        System.out.println("doA");
    }

    /* (non-Javadoc)
     * @see se.ericsson.nrg.ws.adapter.bwlist.DumpHandler#doB(java.lang.String, int, java.util.Date, java.lang.Long)
     */
    @SuppressWarnings("unused")
    public void doB( String a, int b, Date c, Long d) {
        System.out.println("doB");

    }

    /* (non-Javadoc)
     * @see se.ericsson.nrg.ws.adapter.bwlist.DumpHandler#doC(se.ericsson.nrg.ws.adapter.bwlist.DumpDTO, java.lang.String)
     */   
    public DumpDTO doC(DumpDTO dto, String string) {
        System.out.println("doC");
        dto.setId("updateId: " + string);
        return dto;
    }

    /* (non-Javadoc)
     * @see se.ericsson.nrg.ws.adapter.bwlist.DumpHandler#doC(se.ericsson.nrg.ws.adapter.bwlist.DumpDTO[])
     */    
    public List<DumpDTO> doD(DumpDTO[] dto) {
        System.out.println("doD");
        return Arrays.asList(dto);

    }

}

 Junit的代码

public class MethodLoggerHandlerTest extends TestCase {
    private static XmlBeanFactory factory;
    /* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
    @Override
    protected void setUp() throws Exception {        
        super.setUp();
        File file = new File("test/junit/applicationContext.xml");
        if(file.exists()){
            System.out.println("file exits");
        }
        factory = new XmlBeanFactory(new FileSystemResource("test/junit/applicationContext.xml"));
        
    }

    /**
     * unit test
     */
    public void testExecute() {
        DumpHandler handler = (DumpHandler)factory.getBean("dumpHandler");
        DumpDTO[] dtos = new DumpDTO[3];
        for(int i = 0; i < dtos.length; i++) {
            DumpDTO dto = new DumpDTO();
            dto.setId("id" + i);
            dto.setNum(100 + i);
            dto.setTime(new Date());
            dto.setU(1000l + i);
            dtos[i] = dto;
        }
        
        handler.doA();//no log
        handler.doB("a", 100, new Date(), 1000l); //log input
        handler.doC(dtos[0], getName()); // log return only, see annotation defined in DumpHandler
        handler.doD(dtos); // log both input and return
    }
}

 最后是Spring的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <bean id="dumpHandler"
        class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="proxyInterfaces">
            <list>
                <value>xxx.xxx.DumpHandler</value>
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <value>logInterceptor</value>
            </list>
        </property>
        <property name="target">
            <ref bean="testImpl" />
        </property>
    </bean>
    
    <bean id="logInterceptor" class="xxx.xxx.MethodLoggerInterceptor ">        
    </bean>

    <bean id="testImpl" class="xxx.xxx.DumpHandlerImpl">        
    </bean>       


</beans>

 OK,完工。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值