切面打印完整日志,以下代码用于扫描@RestController 注解修饰的接口,并打印相关日志文章来源地址https://www.toymoban.com/news/detail-626444.html
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.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
public class RequestLoggingAspect {
private final Logger logger = LoggerFactory.getLogger(RequestLoggingAspect.class);
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void controller() {
}
@Before("controller()")
public void logBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("Request URL: {}", request.getRequestURL());
logger.info("HTTP Method: {}", request.getMethod());
logger.info("IP Address: {}", request.getRemoteAddr());
logger.info("Class Method: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
logger.info("Request Parameters: {}", Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(pointcut = "controller()", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info("Response: {}", result);
}
}
文章来源:https://www.toymoban.com/news/detail-626444.html
到了这里,关于Springboot切面打印日志的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!