SpringBoot全局统⼀记录⽇志
1.记录⽇志
使⽤aop来记录controller中的请求返回⽇志
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
在完成了引⼊AOP依赖包后,⼀般来说并不需要去做其他配置。也许在Spring中使⽤过注解配置⽅式的⼈会问是否需要在程序主类中增加@EnableAspectJAutoProxy来启⽤,实际并不需要。
可以看下⾯关于AOP的默认配置属性,其中spring.aop.auto属性默认是开启的,也就是说只要引⼊了AOP依赖后,默认已经增加了@EnableAspectJAutoProxy。
# 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.使⽤Around
@Aspect
@Component
public class ControllerAspect {
private Logger logger = Logger(getClass());
/**
* Controller aspect.
*/
@Pointcut("execution(* com.shitou.huishi.service..*.*(..))")
public void controllerAspect() {
}
/**
* Around ⼿动控制调⽤核⼼业务逻辑,以及调⽤前和调⽤后的处理,
* <p>
* 注意:当核⼼业务抛异常后,⽴即退出,转向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 = RequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = Request();
springboot aoplogger.info("URL : " + RequestURL().toString());
logger.info("HTTP_METHOD : " + Method());
logger.info("IP : " + RemoteAddr());
logger.info("CLASS_METHOD : " + Signature().getDeclaringTypeName() + "." + Signature().getName());
logger.info("REQUEST ARGS : " + Args()));
long startTime = System.currentTimeMillis();
try {
Object response = pjp.proceed();
// 2.打印出参,返回结果
long endTime = System.currentTimeMillis();
// 3.出参打印
logger.info("RESPONSE:{}", response != null ? JSONString(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) {
<("RESPONSE ERROR:{}", StackTrace()));
throw e;
} finally {
long endTime = System.currentTimeMillis();
<("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.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
/**
* Created by qhong on 2018/5/28 14:25
**/
@Aspect
@Component
public class LogAspect {
private Logger logger = Logger(getClass());
ThreadLocal<Long> 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) RequestAttributes();
HttpServletRequest request = Request();
// 记录下请求内容
logger.info("URL : " + RequestURL().toString());
logger.info("HTTP_METHOD : " + Method());
logger.info("IP : " + RemoteAddr());
logger.info("CLASS_METHOD : " + Signature().getDeclaringTypeName() + "." + Signature().getName());        logger.info("ARGS : " + Args()));
}
@AfterReturning(returning = "ret", pointcut = "logAspect()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - ()));
}
}
两种⽅式计算出来的时间,参数,返回体是⼀样的。
完善版本:
import com.alibaba.fastjson.JSON;
import com.ption.AuthException;
import com.ption.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.t.request.RequestAttributes;
import org.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
/**
* 类描述: ⽇志,打印controller层的⼊参和出参<br> 创建时间: 2016/7/29 0029 <br>
*
* @author 李恒
*/
@Aspect
@Component
public class ControllerAspect {
private Logger logger = Logger(getClass());
/**
* Controller aspect.
*/
@Pointcut("execution(* com.shitou.huishi.service..*.*(..))")
public void controllerAspect() {
}
/**
* Around ⼿动控制调⽤核⼼业务逻辑,以及调⽤前和调⽤后的处理,
* <p>
* 注意:当核⼼业务抛异常后,⽴即退出,转向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 = RequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//防⽌不是http请求的⽅法,例如:scheduled
if (ra == null || sra == null) {
return pjp.proceed();
}
HttpServletRequest request = Request();
logger.info("URL : " + RequestURL().toString());
logger.info("HTTP_METHOD : " + Method());
logger.info("IP : " + RemoteAddr());
logger.info("CLASS_METHOD : " + Signature().getDeclaringTypeName() + "." + Signature().getName());        logger.info("REQUEST ARGS : " + Args()));
long startTime = System.currentTimeMillis();
try {
Object response = pjp.proceed();
// 3.出参打印
logger.info("RESPONSE:{}", response != null ? JSONString(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 {
<("RESPONSE ERROR:{}", StackTrace()));
}
throw e;
} finally {
long endTime = System.currentTimeMillis();
logger.info("SPEND TIME : {}ms", (endTime - startTime));
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。