import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
@Slf4j
public class LogAspect {
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
@Pointcut("@annotation(org.cango.bop.util.Log)")
public void serviceLog() {
}
@Around("serviceLog()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Class<?> targetClass = method.getDeclaringClass();
StringBuilder classAndMethod = new StringBuilder();
Log classAnnotation = targetClass.getAnnotation(Log.class);
Log methodAnnotation = method.getAnnotation(Log.class);
if (classAnnotation != null) {
if (classAnnotation.ignore()) {
return joinPoint.proceed();
}
classAndMethod.append(classAnnotation.value()).append("-");
}
if (methodAnnotation != null) {
if (methodAnnotation.ignore()) {
return joinPoint.proceed();
}
classAndMethod.append(methodAnnotation.value());
}
String target = targetClass.getName() + "#" + method.getName();
String params = JSON.toJSONStringWithDateFormat(joinPoint.getArgs(), DATE_TIME_PATTERN, SerializerFeature.WriteMapNullValue);
log.info("{} 开始调用--> {} 参数:{}", classAndMethod, target, params);
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long timeConsuming = System.currentTimeMillis() - start;
log.info("{} 调用结束<-- {} 返回值:{} 耗时:{}ms", classAndMethod, target, JSON.toJSONStringWithDateFormat(result, DATE_TIME_PATTERN, SerializerFeature.WriteMapNullValue), timeConsuming);
return result;
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
/**
* log 说明
*
* @return
*/
String value() default "";
/**
* 是否忽略,比如类上面加的有注解,类中某一个方法不想打印可以设置该属性为 true
*
* @return
*/
boolean ignore() default false;
}
/**
* 饼图数据获取
*
* @param req
* @return
*/
@Log("饼图数据获取")
@PostMapping("/getPieChartData")
public List<PieChartConfigRes> getPieChartData(@RequestBody ChartConfigReq req) {
return null;
}
标签:lang,return,Log,controller,org,import,日志,annotation,参出
From: https://www.cnblogs.com/lovedaodao/p/17702367.html