Springboot使用切面AOP实现调用接口则输出请求IP到日志中
引入Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
代码实现
package com.suntek.app.access.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; 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; import javax.servlet.http.HttpServletRequest; @Component @Aspect public class LogAop { private static final Logger LOG = LoggerFactory.getLogger(LogAop.class); //换行符 private final static String LINE_SEPARATOR = System.lineSeparator(); @Pointcut("execution(public * com.suntek.app.access.controller..*.*(..))") public void apiPointCut() { } @Before("apiPointCut()") public void beforeReturning(JoinPoint joinPoint) { //开始打印请求日志 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String host = request.getHeader("Host"); String nginx = request.getHeader("X-Forwarded-For"); String ip = (nginx != null && !nginx.isEmpty()) ? nginx : host; String method = request.getMethod(); String accessUrl = joinPoint.getSignature().getDeclaringTypeName() + joinPoint.getSignature().getName(); // 打印请求的 IP String remoteIp = request.getRemoteAddr(); if (LOG.isInfoEnabled()) { LOG.info("accessUrl={}, method={}, ip={}, remoteIp={}", accessUrl, method, ip, remoteIp) ; } } }