package com.ly.mp.iov.config;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LoggingAspect {
private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
/*
*定义一个方法,用于声明切点表达式,该方法一般没有方法体
*@Pointcut用来声明切点表达式
*通知直接使用定义的方法名即可引入当前的切点表达式
*/
@Pointcut("execution(* com.ly.mp.iov.service.*.*(..))")
public void pointcutDeclaration() {}
//前置通知,方法执行之前执行
@Before("pointcutDeclaration()")
public void beforeMethod(JoinPoint jp) {
String targetClassName = jp.getTarget().getClass().getName();
String methodName = jp.getSignature().getName();
Object[] args = jp.getArgs();
String param = null;
if( jp.getArgs() != null ) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append( "[" );
for( Object arg : jp.getArgs() )
{
if( stringBuffer.toString().length() > 1 ) {
stringBuffer.append( "," );
}
try {
stringBuffer.append( JSON.toJSONString( arg ) );
}catch (Exception e) {
stringBuffer.append( "unSupportType" );
}
}
stringBuffer.append( "]" );
param = stringBuffer.toString();
}
logger.info( "{}.{} receive data:{}" , targetClassName , methodName , param );
}
//后置通知,方法执行之后执行(不管是否发生异常)
// @After(“pointcutDeclaration()”)
// public void AfterMethod(JoinPoint jp) {
// String methodName = jp.getSignature().getName();
// Object[] args = jp.getArgs();
// System.out.println("AfterMethod The method “+ methodName +” parameter is "+Arrays.asList(args));
// System.out.println();
// }
//返回通知,方法正常执行完毕之后执行
@AfterReturning(value="pointcutDeclaration()",returning="result")
public void afterReturningMethod(JoinPoint jp , Object result) {
String targetClassName = jp.getTarget().getClass().getName();
String methodName = jp.getSignature().getName();
logger.info( "{}.{} return data:{}" , targetClassName , methodName , JSON.toJSONString( result ) );
}
}