package org.rest.util;
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;
}
package org.rest.util;
import java.lang.reflect.Method;
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 com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
@Aspect
@Component
@Slf4j
public class LogAspect {
private String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
@Pointcut("@annotation(org.rest.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 = JSONObject.toJSONStringWithDateFormat(joinPoint.getArgs(), DATE_TIME_PATTERN, SerializerFeature.WriteMapNullValue);
log.info("{} 开始调用--> {} 参数:{}", classAndMethod.toString(), target, params);
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long timeConsuming = System.currentTimeMillis() - start;
log.info("{} 调用结束<-- {} 返回值:{} 耗时:{}ms", classAndMethod.toString(), target, JSONObject.toJSONStringWithDateFormat(result, DATE_TIME_PATTERN, SerializerFeature.WriteMapNullValue), timeConsuming);
return result;
}
}
@Service
@Log("用户登录")
@Slf4j
public class UserServiceImpl implements UserService {
}
标签:lang,springboot,joinPoint,切面,org,import,日志,annotation,Log
From: https://www.cnblogs.com/lovedaodao/p/17503615.html