使用注解方式收集方法日志
使用注解的方式在進入和退出方法時打印日志,計算方法執行時長。
1.注解類
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodCommonLog {
/**
*
* @return
*/
boolean flag() default true;
/**
*
* @return
*/
String hideFeilds() default "";
/**
*
* @return
*/
String description() default "";
}
2.切麵類
import java.lang.reflect.Method;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import com.utils.HiddenUtils;
import com.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.extern.slf4j.Slf4j;
@Aspect
@Slf4j
@Component
public class MethodCommonLogAspect {
private static ThreadLocal<Long> tl = new ThreadLocal<>();
private static final String dateformat = "yyyy:MM:dd HH:mm:ss";
@Pointcut(value = "@annotation(com.hsbc.rbwm.digital.dco.etb.cards.basic.logging.MethodCommonLog)")
public void methodLog() {
}
@Before(value = "methodLog()")
public void doBefore(JoinPoint joinPoint) throws Exception {
Map<String, Object> map = this.getAnnotationLog(joinPoint);
String target = (String) map.get("target");
Map<String, Object> newParams = (Map<String, Object>) map.get("newParams");
MethodCommonLog methodLog = (MethodCommonLog) map.get("methodLog");
log.info("executing method start, method:{}, params:{}", target, JacksonUtils.obj2Str(newParams));
if (methodLog != null && methodLog.flag()) {
//do something
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("Description :" + methodLog.description());
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteUser());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
long beforeTime = System.currentTimeMillis();
tl.set(beforeTime);
}
@AfterReturning(returning = "reValue", pointcut = "methodLog()")
public void doAfterReturning(JoinPoint joinPoint, Object reValue) throws Exception {
long beforeTime = tl.get();
long subTime = System.currentTimeMillis() - beforeTime;
Map<String, Object> map = this.getAnnotationLog(joinPoint);
Map<String, Object> newParams = (Map<String, Object>) map.get("newParams");
String target = (String) map.get("target");
MethodCommonLog methodLog = (MethodCommonLog) map.get("methodLog");
String hideFeilds = methodLog != null?methodLog.hideFeilds():"";
if (reValue instanceof ResponseEntity){
reValue = ((ResponseEntity) reValue).getBody();
}
String returnValueStr = JacksonUtils.obj2Str(reValue).isPresent()?JacksonUtils.obj2Str(reValue).get():"";
Map<String, Object> returnValue = this.getHideParams(hideFeilds,returnValueStr);
log.info("executing method end,method:{}, params:{}, return:{}, spent time:{}", target, newParams, JacksonUtils.obj2Str(returnValue),subTime);
if (methodLog != null && methodLog.flag()) {
//do something
}
}
private Map<String, Object> getAnnotationLog(JoinPoint joinPoint) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("target", null);
resultMap.put("newParams", null);
resultMap.put("methodLog", null);
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
MethodCommonLog methodLog = null;
if (method != null) {
methodLog = method.getAnnotation(MethodCommonLog.class);
resultMap.put("methodLog", methodLog);
String hideFeilds = methodLog.hideFeilds();
Class<?> targetClass = method.getDeclaringClass();
String target = targetClass.getName() + "#" + method.getName();
Object[] args = joinPoint.getArgs();
Map<String, Object> newParams = new HashMap<>();
if (args != null && args.length > 0) {
String param = "";
for (Object arg : args) {
param = JacksonUtils.obj2Str(arg).isPresent() ? JacksonUtils.obj2Str(arg).get() : "";
newParams = this.getHideParams(hideFeilds, param);
}
}
resultMap.put("target", target);
resultMap.put("newParams", newParams);
} else {
log.warn("create method log fail: method is null");
}
return resultMap;
}
private Map<String, Object> getHideParams(String hideFeilds,String param){
Map<String, Object> newParams = new HashMap<>();
if (StringUtils.isNotBlank(param)) {
String[] hideFeildsArr = {};
if (StringUtils.isNotBlank(hideFeilds)) {
hideFeildsArr = hideFeilds.split(",");
}
String hideVal = "";
Optional<Map<String, String>> optionalMap = JacksonUtils.str2Map(param, String.class, String.class);
if (optionalMap.isPresent()) {
Map<String, String> jsonNode = optionalMap.get();
String key = "";
for (Map.Entry<String, String> entry : jsonNode.entrySet()) {
key = entry.getKey();
hideVal = entry.getValue();
for (String feild : hideFeildsArr) {
if (key.equalsIgnoreCase(feild)) {
hideVal = HiddenUtils.characterHidden(entry.getValue());
}
}
newParams.put(key, hideVal);
}
}
}
return newParams;
}
}
以上是 使用注解方式收集方法日志 的全部内容, 来源链接: utcz.com/z/511817.html