SpringAOP实现自动生成日志 【基于java.lang.annotation约定】
- - ITeye博客 项目中总要发布一下服务供系统内外调用,为了方便排查错误,入参出参都要以日志的形式记录下来. 传统做法:缺点一目了然,参数少的时候只能说还好,参数一多,烦不胜烦,浪费时间. 于是借鉴了AOP的思想,将日志功能做成一个切面,横向切入到业务逻辑前后(方法开始前和结束后).
private static final Logger logger = Logger.getLogger(HelloServiceImpl.class); public String sayHello(String name,String words) { logger.info("remote input:name="+name+",words="+words); //业务逻辑 String result = "Hello"+name+","+words); logger.info("remote output:result="+result); return result; }
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AOPLog4jAnnotation { String paramCollection(); }
public class HelloServiceImpl implements HelloService{ @Override @AOPLog4jAnnotation(paramCollection="name,words") public String sayHello(String name,String words) { String text = "Hello "+name+"!"+words+"."; return text; } }
@AOPLog4jAnnotation(paramCollection="name,words")
<bean id="helloService" class="com.aop.log4j.service.impl.HelloServiceImpl" /> <bean id="aspect" class="com.aop.log4j.aspect.HelloAspect"/> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.aop.log4j.service.HelloService.*(..)))" /> <aop:aspect ref="aspect"> <aop:around pointcut-ref="pointcut" method="arround"/> </aop:aspect> </aop:config>
public class HelloAspect { private static final Logger logger = Logger.getLogger(HelloAspect.class); private static final String DOT = ".";//点号 private static final String COMMA = ",";//逗号 public void arround(ProceedingJoinPoint joinPoint) throws Throwable { StringBuilder sb = new StringBuilder(); Object[] paramValues = joinPoint.getArgs();//获取参数值 String[] paramNames = new String[paramValues.length]; Method methods[] = joinPoint.getTarget().getClass().getMethods(); for (Method method : methods) { if(method.getName().equals(joinPoint.getSignature().getName())) { String paramCollection = method.getAnnotation (AOPLog4jAnnotation.class).paramCollection();//获取注解值 String[] names = paramCollection.split(COMMA); System.arraycopy(names, 0, paramNames, 0, names.length); } } for (int i = 0; i < paramValues.length; i++) { sb.append(paramNames[i] + "=" + paramValues[i] + COMMA); } //入参日志 logger.info(joinPoint.getTarget().getClass() + DOT + joinPoint. getSignature().getName() + ",remote input:" + sb.toString().substring(0, sb.length() - 1)); try { Object result = joinPoint.proceed(); //出参日志 logger.info(joinPoint.getTarget().getClass() + DOT+joinPoint. getSignature().getName() + ",remote output:" + result); } catch (Exception e) { logger.error(joinPoint.getTarget().getClass() + DOT+joinPoint. getSignature().getName() + " invoke error"); } } }
[INFO] 2012-10-03 11:54:29,807 [com.aop.log4j.aspect.HelloAspect.arround] - class com.aop.log4j.service.impl.HelloServiceImpl.sayHello,remote input:name=Java,words=I love you. [INFO] 2012-10-03 11:54:29,808 [com.aop.log4j.aspect.HelloAspect.arround] - class com.aop.log4j.service.impl.HelloServiceImpl.sayHello,remote output:Hello Java!I love you.