SpringBootグローバル統一記録ログ
20325 ワード
1.ログを記録する
aopを使ってcontrollerの要求を記録してログに戻ります.
pom.xml導入:
AOPのデフォルトの設定属性については、spring.aop.aut属性はデフォルトでオープンしています.つまり、AOP依存を導入すると、デフォルトでは@EnbleAspectJAtoxyが増加しています.
1.Aoundを使う
2.Beforeを使って、AfterReturning処理:
完全バージョン:
http://blog.didispace.com/springbootaoplog/
http://blog.didispace.com/springbootexception/
aopを使ってcontrollerの要求を記録してログに戻ります.
pom.xml導入:
org.springframework.boot
spring-boot-starter-aop
AOP依存パッケージの導入が完了したら、一般的に他の構成をする必要はありません.Springで注釈の配置を使ったことがある人は、プログラムのメインクラスに@EnbleAspectJAtoProxyを追加する必要がありますか?AOPのデフォルトの設定属性については、spring.aop.aut属性はデフォルトでオープンしています.つまり、AOP依存を導入すると、デフォルトでは@EnbleAspectJAtoxyが増加しています.
# AOP
spring.aop.auto=true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class=false # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false).
1.Aoundを使う
@Aspect
@Component
public class ControllerAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* Controller aspect.
*/
@Pointcut("execution(* com.shitou.huishi.service..*.*(..))")
public void controllerAspect() {
}
/**
* Around , ,
*
* : , , AfterAdvice AfterAdvice, ThrowingAdvice
*
* @param pjp
* the pjp
* @return object
* @throws Throwable
* the throwable
*/
@Around(value = "controllerAspect()")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
logger.info("REQUEST ARGS : " + JSON.toJSONString(pjp.getArgs()));
long startTime = System.currentTimeMillis();
try {
Object response = pjp.proceed();
// 2. ,
long endTime = System.currentTimeMillis();
// 3.
logger.info("RESPONSE:{}", response != null ? JSON.toJSONString(response) : "");
logger.info("SPEND TIME : {}ms", (endTime - startTime));
return response;
} catch (AuthException e) {
logger.info("RESPONSE ERROR:{}", e.getMsg());
throw e;
} catch (HuishiApiException e) {
logger.info("RESPONSE ERROR:{}", e.getMsg());
throw e;
} catch (MethodArgumentNotValidException e) {
logger.info("RESPONSE ERROR:{}", e.getMessage());
throw e;
} catch (Throwable e) {
logger.error("RESPONSE ERROR:{}", Arrays.toString(e.getStackTrace()));
throw e;
} finally {
long endTime = System.currentTimeMillis();
logger.error("SPEND TIME : {}ms", (endTime - startTime));
}
}
}
2.Beforeを使って、AfterReturning処理:
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
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;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Created by qhong on 2018/5/28 14:25
**/
@Aspect
@Component
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
ThreadLocal startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.shitou.huishi.service.*.*(..))")
public void logAspect(){}
@Before("logAspect()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// ,
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "logAspect()")
public void doAfterReturning(Object ret) throws Throwable {
// ,
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
}
二つの方法で計算した時間、パラメータ、リターンは同じです.完全バージョン:
import com.alibaba.fastjson.JSON;
import com.shitou.huishi.contract.datacontract.exception.AuthException;
import com.shitou.huishi.contract.datacontract.exception.HuishiApiException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* : , controller
: 2016/7/29 0029
*
* @author
*/
@Aspect
@Component
public class ControllerAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* Controller aspect.
*/
@Pointcut("execution(* com.shitou.huishi.service..*.*(..))")
public void controllerAspect() {
}
/**
* Around , ,
*
* : , , AfterAdvice AfterAdvice, ThrowingAdvice
*
* @param pjp the pjp
* @return object
* @throws Throwable the throwable
*/
@Around(value = "controllerAspect()")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
// http , :scheduled
if (ra == null || sra == null) {
return pjp.proceed();
}
HttpServletRequest request = sra.getRequest();
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
logger.info("REQUEST ARGS : " + JSON.toJSONString(pjp.getArgs()));
long startTime = System.currentTimeMillis();
try {
Object response = pjp.proceed();
// 3.
logger.info("RESPONSE:{}", response != null ? JSON.toJSONString(response) : "");
return response;
} catch (Throwable e) {
if (e instanceof AuthException) {
logger.info("RESPONSE ERROR:{}", ((AuthException) e).getMsg());
} else if (e instanceof HuishiApiException) {
logger.info("RESPONSE ERROR:{}", ((HuishiApiException) e).getMsg());
} else if (e instanceof MethodArgumentNotValidException) {
logger.info("RESPONSE ERROR:{}", e.getMessage());
} else {
logger.error("RESPONSE ERROR:{}", Arrays.toString(e.getStackTrace()));
}
throw e;
} finally {
long endTime = System.currentTimeMillis();
logger.info("SPEND TIME : {}ms", (endTime - startTime));
}
}
}
http://blog.didispace.com/springbootaoplog/
http://blog.didispace.com/springbootexception/