@Aspect
@Order(5)
@Component
public class ControllerLogAspect {
private static final Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);
@Value("${controller.log.level:0}")
private int controllerLogLevel;
@Pointcut("execution(public * com.test.controller..*.*(..))")
public void controllerLog() {
}
@Before("controllerLog()")
public void before(JoinPoint joinPoint) throws Exception {
if (controllerLogLevel == Const.ControllerLogLevel.REQUEST_ONLY || controllerLogLevel == Const.ControllerLogLevel.REQUEST_RESPONSE_BOTH) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String contentType = request.getContentType();
printFormParam(request);
printBodyParam(contentType, joinPoint);
}
}
@AfterReturning(returning = "ret", pointcut = "controllerLog()")
public void afterReturning(Object ret) throws Exception {
if (controllerLogLevel == Const.ControllerLogLevel.RESPONSE_ONLY || controllerLogLevel == Const.ControllerLogLevel.REQUEST_RESPONSE_BOTH) {
logger.info("Servlet Response: {}", JsonUtil.toJson(ret));
}
}
private void printBodyParam(String contentType, JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
if (args.length > 0) {
for (Object arg : args) {
if (arg instanceof HttpServletRequest || arg instanceof HttpServletResponse) {
continue;
}
if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
logger.info("Servlet Request body: {}", JsonUtil.toJson(arg));
}
}
}
}
private void printFormParam(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
if (!parameterMap.isEmpty()) {
StringBuilder param = new StringBuilder();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
param.append(entry.getKey()).append("-").append(Arrays.toString(entry.getValue())).append(" ");
}
logger.info("Servlet Request Form: {}", param.toString());
}
}
}
public interface ControllerLogLevel {
int NONE = 0;
int REQUEST_ONLY = 1;
int RESPONSE_ONLY = 2;
int REQUEST_RESPONSE_BOTH = 3;
}