1.使用springAOP切面拦截所有controller请求
1.添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2.添加aspect包下的LogAspect文件
package com.futureport.wiki.aspect;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.futureport.wiki.utils.RequestContext;
import com.futureport.wiki.utils.SnowFlake;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
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.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class LogAspect {
@Resource
SnowFlake snowFlake;
private final static Logger LOG = LoggerFactory.getLogger(LogAspect.class);
/** 定义一个切点 */
@Pointcut("execution(public * com.futureport.*.controller..*Controller.*(..))")
public void controllerPointcut() {}
@Before("controllerPointcut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 增加日志流水号
MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Signature signature = joinPoint.getSignature();
String name = signature.getName();
// 打印请求信息
LOG.info("------------- 开始 -------------");
LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
LOG.info("类名方法: {}.{}", signature.getDeclaringTypeName(), name);
LOG.info("远程地址: {}", request.getRemoteAddr());
RequestContext.setRemoteAddr(getRemoteIp(request));
// 打印请求参数
Object[] args = joinPoint.getArgs();
// LOG.info("请求参数: {}", JSONObject.toJSONString(args));
Object[] arguments = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest
|| args[i] instanceof ServletResponse
|| args[i] instanceof MultipartFile) {
continue;
}
arguments[i] = args[i];
}
// 排除字段,敏感字段或太长的字段不显示
String[] excludeProperties = {"password", "file"};
PropertyPreFilters filters = new PropertyPreFilters();
PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
excludefilter.addExcludes(excludeProperties);
LOG.info("请求参数: {}", JSONObject.toJSONString(arguments, excludefilter));
}
@Around("controllerPointcut()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 排除字段,敏感字段或太长的字段不显示
String[] excludeProperties = {"password", "file"};
PropertyPreFilters filters = new PropertyPreFilters();
PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
excludefilter.addExcludes(excludeProperties);
LOG.info("返回结果: {}", JSONObject.toJSONString(result, excludefilter));
LOG.info("------------- 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
return result;
}
/**
* 使用nginx做反向代理,需要用该方法才能取到真实的远程IP
* @param request
* @return
*/
public String getRemoteIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
2.加到方法上拦截指定的controller或者service
1.添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2.添加annotation包下的ControllerLog和ServiceLog文件
ControllerLog
package com.futureport.wiki.annotation;
import java.lang.annotation.*;
/**
* ClassName: ControllerLog
* Description: 自定义注解 拦截Controller
* date: 2021/9/7 1:37 PM
*
* @author zhihao.huang
* Copyright (c) 2019. convertlab.com All Rights Reserved.
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
String description() default "";
}
ServiceLog
package com.futureport.wiki.annotation;
import java.lang.annotation.*;
/**
* ClassName: ServiceLog
* Description: 自定义注解 拦截service
* date: 2021/9/7 1:37 PM
*
* @author zhihao.huang
* Copyright (c) 2019. convertlab.com All Rights Reserved.
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ServiceLog {
String description() default "";
}
3.添加aspect包下的SystemLogAspect文件
package com.futureport.wiki.aspect;
import com.alibaba.fastjson.JSONObject;
import com.futureport.wiki.annotation.ControllerLog;
import com.futureport.wiki.annotation.ServiceLog;
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 java.lang.reflect.Method;
/**
* ClassName: SystemLogAspect
* Description: 通用日志切点类
* date: 2021/9/7 1:37 PM
*
* @author zhihao.huang
* Copyright (c) 2019. convertlab.com All Rights Reserved.
*/
@Aspect
@Component
public class SystemLogAspect {
private final static Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
//Service层切点
@Pointcut("@annotation(com.futureport.wiki.annotation.ServiceLog)")
public void serviceAspect() {
}
//Controller层切点
@Pointcut("@annotation(com.futureport.wiki.annotation.ControllerLog)")
public void controllerAspect() {
}
public SystemLogAspect(){
logger.info("@@@ start SystemLogAspect ");
}
/**
* 前置通知 用于拦截Controller层记录用户的操作
*
* @param joinPoint 切点
*/
@Before("controllerAspect()")
public void doBefore4control(JoinPoint joinPoint) {
try {
Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
log.info(">>> Execute Controller: {}.{}()", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
} catch (Exception e) {
e.printStackTrace();
if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in doBefore4control: {}", e.getMessage());
}else{
logger.error("Exception in doBefore4control: {}", e.getMessage());
}
}
}
@Before("serviceAspect()")
public void doBefore4service(JoinPoint joinPoint) {
try {
String params = "";
if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
for ( int i = 0; i < joinPoint.getArgs().length; i++) {
try {
params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
}catch (Exception e){}
}
}
Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
log.info(">>> Execute Service: {}.{}({})", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), params);
} catch (Exception ex) {
ex.printStackTrace();
if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in doBefore4service: {}", ex.getMessage());
}else{
logger.error("Exception in doBefore4control: {}", ex.getMessage());
}
}
}
@AfterReturning(pointcut="serviceAspect()", returning="returnValue")
public void after4service(JoinPoint joinPoint, Object returnValue) {
try {
Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
String response = "";
try{
response = JSONObject.toJSON(returnValue).toString();
}catch (Exception e){
}
log.info("<<<< Service : {}.{}() Response. {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), response);
} catch (Exception ex) {
ex.printStackTrace();
if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in after4service: {}", ex.getMessage());
}else{
logger.error("Exception in doBefore4control: {}", ex.getMessage());
}
}
}
/**
* 获取注解中对方法的描述信息 用于service层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public static String getServiceMethodDescription(JoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(ServiceLog.class).description();
break;
}
}
}
return description;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(ControllerLog.class).description();
break;
}
}
}
return description;
}
}
4.在controller和service文件中使用自定义注解
@ControllerLog
@RequestMapping("/ebook/list")
public CommonResp ebook(EbookReq req) {
CommonResp<List<EbookResp>> resp = new CommonResp<>();
@ServiceLog
public List<EbookResp> list(EbookReq req) {
EbookExample ebookExample = new EbookExample();