1. 程式人生 > >spring aop :logaspect配置

spring aop :logaspect配置

spring.xml

    <context:component-scan base-package="xx.xx.aspect" />
    <aop:aspectj-autoproxy />
    <aop:config>    
        <aop:aspect id="logAspect" ref="logAspect">
            <aop:pointcut expression="execution(public * XX.XX.front.service.ws.impl.*.*(..))" id="logPoint"
/>
<aop:before method="doBefore" pointcut-ref="logPoint"/> <aop:after-returning method="doAfter" returning="retValue" pointcut-ref="logPoint"/> </aop:aspect> </aop:config>

pom.xml

<dependency>
            <groupId>org.springframework</groupId
>
<artifactId>spring-aop</artifactId> <version>${version.spring}</version> </dependency>

logAspect.java

package xx.xx.aspect;

import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import
org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import cfca.seal.common.Constants; @Component @Aspect public class LogAspect { private static final Logger logger = LoggerFactory.getLogger(Constants.SERVICE_SYS); long startTime; /** * service 類 方法起始 引數 列印 * @param joinPoint */ public void doBefore(JoinPoint joinPoint) { startTime = cfca.itool.util.TimeUtil.getNowTimeInMillis(); //System.out.println(buildLog(joinPoint,null,null)); } /** * service 類 方法結束 引數 列印 * @param joinPoint * @param retValue */ public void doAfter(JoinPoint joinPoint, Object retValue) { String className = joinPoint.getTarget().getClass().getSimpleName(); String methodName = joinPoint.getSignature().getName(); long endTime = cfca.itool.util.TimeUtil.getNowTimeInMillis(); logger.info("["+className+"."+methodName+"]"+"耗時:"+(endTime-startTime)+"ms"); // System.out.println(buildLog(joinPoint,retValue,null)); } /** * service 類 方法異常 引數 列印 * @param joinPoint * @param e */ public void doThrowException(JoinPoint joinPoint, Exception e) { //System.out.println(buildLog(joinPoint,null,e)); } @SuppressWarnings("rawtypes") private String buildLog(JoinPoint joinPoint,Object retValue, Exception e){ StringBuffer sb=new StringBuffer(); String className = joinPoint.getTarget().getClass().getSimpleName(); String methodName = joinPoint.getSignature().getName(); sb.append("[ClassMethod:").append(className).append(".").append(methodName).append("]"); Object[] obj = joinPoint.getArgs(); sb.append("[requestParam:"); for (int i = 0; i < obj.length; i++) { sb.append("引數arg").append(i).append(":").append(obj[i]); } sb.append("]"); if(retValue!=null){ sb.append("[result:"); if(retValue instanceof List){ sb.append("size()=").append(((List) retValue).size()) ; }else{ sb.append(retValue.toString()); } } if(e!=null){ sb.append("[errorMsg:").append(e.getMessage()).append("],").append(e); } return sb.toString(); } }