SpringBoot項目優雅日誌打印請求參數及返回參數:
需求:1:請求參數及響應內容日誌打印交給切面進行管理,避免手動創建log對象進行日誌記錄打印
2:基於註解的Controller的Method,添加註解進行打印,不添加註解不打印日誌,便於根據實際情況日誌的輸出.
步驟:
添加依賴:
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
創建自定義註解:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)//註解不僅被保存到class文件中,jvm加載class文件之後,仍存在
@Target(ElementType.METHOD) //註解添加的位置
@Documented
public @interface LogPrint {
String description() default "";
}
寫一個切面類進行日誌輸出管理:
package com.group.**.config.aspect;
import com.alibaba.fastjson.JSONObject;
import com.techsun.industry.config.annotation.LogPrint;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Profile;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Aspect
@Component
@Profile({"dev","test"}) //一般生產環境不允許日誌打印參數
@Slf4j
public class LogPrintAspect {
/** 換行符 */
private static final String LINE_SEPARATOR = System.lineSeparator();
/** 以自定義 @LogPrint 註解爲切點 */
@Pointcut("@annotation(com.*.*.config.annotation.LogPrint)")
public void logPrint() {}
/**
* 在切點之前織入
* @param joinPoint
* @throws Throwable
*/
@Before("logPrint()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 開始打印請求日誌
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 獲取 @WebLog 註解的描述信息
String methodDescription = getAspectLogDescription(joinPoint);
// 打印請求相關參數
log.info("========================================== Start ==========================================");
// 打印請求 url
log.info("URL : {}", request.getRequestURL().toString());
// 打印描述信息
log.info("Description : {}", methodDescription);
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// 打印調用 controller 的全路徑以及執行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印請求的 IP
log.info("IP : {}", request.getRemoteAddr());
// 打印請求入參
log.info("Request Args : {}", getParams(joinPoint));
}
/**
* 在切點之後織入
* @throws Throwable
*/
@After("logPrint()")
public void doAfter() throws Throwable {
// 接口結束後換行,方便分割查看
log.info("=========================================== End ===========================================" + LINE_SEPARATOR);
}
/**
* 環繞
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("logPrint()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 打印出參
log.info("Response Args : {}", JSONObject.toJSONString(result));
// 執行耗時
log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
return result;
}
/**
* 獲取切面註解的描述
*
* @param joinPoint 切點
* @return 描述信息
* @throws Exception
*/
public String getAspectLogDescription(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();
StringBuilder description = new StringBuilder("");
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description.append(method.getAnnotation(LogPrint.class).description());
break;
}
}
}
return description.toString();
}
private String getParams(JoinPoint joinPoint) {
String params = "";
if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
for (int i = 0; i < joinPoint.getArgs().length; i++) {
Object arg = joinPoint.getArgs()[i];
if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
|| (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
continue;
}
try {
params +=JSONObject.toJSONString(joinPoint.getArgs()[i]);
} catch (Exception e1) {
log.error(e1.getMessage());
}
}
}
return params;
}
}
現在看看效果吧:
完!!!