springboot有很多方法处理日志,例如拦截器,aop切面,service中代码记录等,
这些方法各有优劣,拦截器处理起来看似简单,但在获取入参之后必须重写RequestWrapper类,否则会报HttpMessageNotReadableException: Required request body is missing异常。如何处理这种异常可以见文章:在拦截器种使用了request.getInputStream()或者getReader(),导致在controller中无法获取请求参数_慕枫520的博客-CSDN博客_controller无法获取参数问题描述:在拦截器种使用了request.getInputStream()或者getReader(),然后在controller接口种使用了@requestbody ,导致controller中无法获取入参,报错:HttpMessageNotReadableException: Required request body is missing:原因分析:ServletRequest中getReader()和getInputStream()只能调用一次。而又由于@RequestBody注解获取输出https://blog.csdn.net/qq_20446879/article/details/120693963
在service中使用代码记录虽然简单自由,但是在开发工作量大的时候会显得异常繁琐,不适合大量开发任务的编程工作。
而使用aop切面编程处理则简单轻松许多,即可以避免重复开发,又不用考虑请求body丢失问题。
这里我们以aop切面为例:
引入aop依赖和日志依赖:
<!-- spring-boot aop 依赖。 start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- spring-boot aop 依赖。 end -->
<!--logger日志 start-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--logger日志 end-->
aop代码:
import com.example.empboxwarehousing.common.util.IpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* 切面处理,记录入参,出参,异常信息
*
* @author chp
* @date 2022-06-08
*/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
/**
* aop签名
*/
@Pointcut("execution(* com.example.empboxwarehousing.*.controller.*.*(..))")
public void webLog() {
}
/**
* 切面处理--->>>事前处理
*
* @param joinPoint JoinPoint联机对象
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
//收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("请求METHOD,URL : {},{}", request.getMethod(), request.getRequestURL());
log.info("请求IP :{} ", IpUtil.getIpAddr(request));
log.info("请求处理CLASS_METHOD : {}", joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
log.info("请求参数:{} : " + Arrays.toString(joinPoint.getArgs()));
}
/**
* 切面--->>>异常处理、
*
* @param ex 异常信息
* @param point JoinPoint联机对象
*/
@AfterThrowing(throwing = "ex", pointcut = "webLog()")
public void doRecoveryActions(JoinPoint point, Throwable ex) {
String className = point.getTarget().getClass().getSimpleName() + "[" + point.getSignature().getName() + "]";
log.error("[Result] 异常" + className + "" + " 返回 " + ex);
}
/**
* 切面--->>>事后处理
*
* @param res 返回值
*/
@AfterReturning(returning = "res", pointcut = "webLog()")
public void doAfterReturning(Object res) throws JsonProcessingException {
//获取返回值
log.info("返回值 : " + new ObjectMapper().writeValueAsString(res));
}
}
这里要注意点是 AOP中@Pointcut切入点表达式的使用,不能使用execution(public * *(..)) ,这个代表切入全部请求,会在启动项目的时候报空指针异常,因为启动项目时候无法获取request。所以建议切入点表达式指定为controller包下的方法。
IpUtil.getIpAddr(request)方法为获取请求者的IP地址的方法,代码如下:
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
/**
* ip处理
* Created by chenpeng on 2022/06/07.
*/
public class IpUtil {
/**
* 获取访问用户的客户端IP(适用于公网与局域网).
*/
public static String getIpAddr(HttpServletRequest request){
try{
if (request == null) {
//throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
return "";
}
String ipString = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
ipString = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
ipString = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
ipString = request.getRemoteAddr();
}
// 多个路由时,取第一个非unknown的ip
String[] arr = ipString.split(",");
for (String str : arr) {
if (!"unknown".equalsIgnoreCase(new StringBuffer(str).toString())) {
ipString = str;
break;
}
}
if(ipString.equals("0:0:0:0:0:0:0:1")){
ipString = "127.0.0.1";
}
return ipString;
}catch(Exception e){
return "";
}
}
}
执行效果如下: