获取请求参数与返回参数
第一种
package xxx.xxx;
import java.lang.annotation.*;
/**
* 系统日志注解
* 注释在控制器上
* @author Mark sunlightcs@gmail.com
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
package com.shinkeer.core.config.aop;
import com.shinkeer.core.utils.JsonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @description: 日志切面打印
**/
@Aspect
@Component
public class LogAop {
private Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(xxx.xxx.SysLog)")
private void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature ms = (MethodSignature) point.getSignature();
Method method = ms.getMethod();
logger.info("===============请求内容===============");
logger.info("请求地址:" + point.getTarget().getClass().getName());
logger.info("请求方式:" + method);
logger.info("请求类方法:" + point.getSignature().getName());
logger.info("请求类方法参数:" + JsonUtils.getJsonString(point.getArgs()));
logger.info("===============请求内容===============");
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
logger.info("===============返回内容===============");
String jsonString = JsonUtils.getJsonString(result);
if (jsonString.length() > 10000) {
logger.info("Response内容:" + "返回内容过大");
} else {
logger.info("Response内容:" + jsonString);
}
logger.info("请求响应时间:" + time + "ms");
logger.info("===============返回内容===============");
return result;
}
}
第二种
package com.cn.cn.annotation.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
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 javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Slf4j
@Component
@Order(1)
public class LogAspect {
@Pointcut("execution(* com.cn..*.*Controller.*(..))")
public void webLog() {
}
/**
* @Description: 前置通知--接口请求信息
**/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
//收到请求,记录请求内容
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
//记录请求url
log.info("URL: " + request.getRequestURL().toString());
//记录请求方法
log.info("REQUEST: " + request.getMethod());
log.info("REQUEST_METHOD: " + joinPoint.getSignature());
//获取请求参数
requestParam(joinPoint);
//记录请求IP
log.info("IP: " + getIpAddress(request));
}
}
/**
* @Description: 请求参数
**/
public void requestParam(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
// 参数名数组
String[] parameterNames = ((MethodSignature) signature).getParameterNames();
// 构造参数组集合
Map<Object, Object> map = new HashMap<>();
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
//request/response无法使用toJSON
if (args[i] instanceof HttpServletRequest) {
map.put(JSON.toJSON(parameterNames[i]), "request");
} else if (args[i] instanceof HttpServletResponse) {
map.put(JSON.toJSON(parameterNames[i]), "response");
} else {
map.put(JSON.toJSON(parameterNames[i]), JSON.toJSON(args[i]));
}
}
log.info("REQUEST_PARAM: {}", JSON.toJSON(map));
}
/**
* @Description: 环绕通知--统计接口耗时 强制加入环绕 正式环境可以取消
**/
@Around("webLog()")
public Object around(ProceedingJoinPoint point) throws Throwable {
//接口时长
long start = System.currentTimeMillis();
Object result = point.proceed();
long end = System.currentTimeMillis();
long elapsedTime = start - end;
log.info("INTERFACE_ELAPSED_TIME : {} ms", elapsedTime);
return result;
}
/**
* @Description: 后置通知--接口返回参数
**/
@AfterReturning(returning = "returnValue", pointcut = "webLog()")
public void doAfterReturning(Object returnValue) throws JsonProcessingException {
JSONObject responseParam = JSON.parseObject(new ObjectMapper().writeValueAsString(returnValue));
//处理完请求,返回内容
log.info("RESPONSE_PARAM : {}", responseParam);
}
/**
* @Description: 异常通知--打印异常信息
**/
@AfterThrowing(value = "webLog()", throwing = "exception")
public void doAfterThrowingAdvice(JoinPoint joinPoint, Exception exception) {
//收到请求,记录请求内容
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
//记录请求url
log.info("URL: {}", request.getRequestURL().toString());
//记录请求方法
log.info("REQUEST: {}", request.getMethod());
log.info("REQUEST_METHOD: {}", joinPoint.getSignature());
//记录请求IP
log.info("IP: {}", getIpAddress(request));
//异常信息
log.info("EXCEPTION: {}", exception.getMessage());
}
}
/**
* @Description: 获取目标主机的ip
**/
public String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192856.html