RequestAop.java 5.86 KB
Newer Older
rex.tan committed
1 2 3 4
package cn.timer.api.aspect;

import java.io.PrintWriter;
import java.io.StringWriter;
rex.tan committed
5 6
import java.text.SimpleDateFormat;
import java.util.Date;
rex.tan committed
7
import java.util.Enumeration;
rex.tan committed
8
import java.util.TimeZone;
rex.tan committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.timer.api.config.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

/**
 * 拦截输出异常堆栈(改用fluentd方式)
 * 
 * @author Rex.Tan 
 * @date 2018年12月13日 上午9:18:58
 */
@Slf4j
@Aspect
@Component
@Order(999)
public class RequestAop {

	@Pointcut("execution(* cn.timer..*.*Controller.*(..))")
	public void init() {

	}

	@Before("init()")
	public void beforeAdvice(JoinPoint joinPoint) {
		// 进入方法前拦截
	}

	@Around("init()")
	public Object around(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String url = request.getRequestURI();
57

rex.tan committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
		/**
		 * 输出url
		 */
		Object obj = null;
		String bodyArgs = this.bodyArgs2String(request, pjp.getArgs(), url);
		JSONObject urlArgs = this.urlArgs2String(request, request.getParameterNames(), url);
		try {
			obj = pjp.proceed();
			long endTime = System.currentTimeMillis();
			this.logInfo2Kafka(request, url, bodyArgs, urlArgs, "success", 0, endTime - startTime, true);
		} catch (Throwable e) {
			e.printStackTrace();
			long endTime = System.currentTimeMillis();
			if (e instanceof CustomException) {
				/**
				 * 拦截到主动抛出的异常
				 */
				CustomException ex = (CustomException) e;
				this.logInfo2Kafka(request, url, bodyArgs, urlArgs, ex.getMessage(), 400, endTime - startTime, false);
				throw ex;
			} else {
				/**
				 * 拦截到未知异常
				 */
				StringWriter stringWriter = new StringWriter();
				e.printStackTrace(new PrintWriter(stringWriter));
				this.logInfo2Kafka(request, url, bodyArgs, urlArgs, "未捕获异常: " + stringWriter.toString(), 500, endTime - startTime, false);
				throw new CustomException("未捕获异常," + e.getMessage());
			}
		} finally {
			
		}

		return obj;
	}

	/**
	 * 请录请求耗时
	 * 
	 * @author Rex.Tan
	 * @date 2018年12月13日 下午2:51:31
	 * @param url           请求地址
	 * @param args          requestBody中的参数
	 * @param args2         url中的参数
	 * @param message       消息
	 * @param status        接口调用返回状态
	 * @param executionTime 执行耗时
	 * @param isSuccess     是否调用成功
	 */
	@Async
	public void logInfo2Kafka(HttpServletRequest request, String url, String bodyArgs, JSONObject urlArgs,
			String message, Integer status, long executionTime, boolean isSuccess) {
		JSONObject json = new JSONObject();
		json.put("logType", "___rest___");
		//		if (UserContext.get() != null) {
		//			json.put("userName", UserContext.get().getUsername());
		//		}
		json.put("url", url);
		json.put("timestamp", System.currentTimeMillis());
rex.tan committed
117
		json.put("visitTime", now2String());
rex.tan committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
		json.put("message", message);
		json.put("status", status);
		json.put("executionTime", executionTime);
		json.put("channel", request.getHeader("channel"));
		json.put("projectName", "8timer");
		json.put("requestType", request.getMethod());
		/**
		 * 1.requestBody中的参数
		 */
		json.put("bodyArgs", bodyArgs);
		/**
		 * 2.url中的参数
		 */
		json.put("urlArgs", urlArgs);
		/**
		 * 3.如果请求状态不为0, 在控制台输入请求信息
		 */
		if (status != 0) {
			log.error("\r\n" + json.toJSONString());
		} else {
			log.info("\r\n" + json.toJSONString());
		}
	}

	/**
	 * 读取requestBody中的参数
	 * 
	 * @author Rex.Tan
	 * @date 2018年12月13日 下午2:54:31
	 * @param bodyArgs
	 * @param url
	 * @return
	 */
	private String bodyArgs2String(HttpServletRequest request, Object[] bodyArgs, String url) {
		if ("GET".equals(request.getMethod())) {
			return "";
		}
284718418@qq.com committed
155
		if (url != null && url.indexOf("/upload")!=-1) {
rex.tan committed
156 157
			return "";
		}
284718418@qq.com committed
158
		if (url != null && url.indexOf("/image")!=-1) {
rex.tan committed
159 160 161 162 163
			return "";
		}
		try {
			if (bodyArgs != null && bodyArgs.length > 0) {
				String body = JSONArray.toJSONString(bodyArgs);
284718418@qq.com committed
164
				if (body.indexOf("/image")!=-1) {
rex.tan committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
					return "";
				}
				return body;
			}
		} catch (Exception e) {
			log.error("=============序列化requestBody中的参数出错, " + url);
		}
		return "";
	}

	/**
	 * 读取url中的参数
	 * 
	 * @author Rex.Tan
	 * @date 2019年9月12日 下午2:54:40
	 * @param request
	 * @param urlArgs
	 * @param url
	 * @return
	 */
	private JSONObject urlArgs2String(HttpServletRequest request, Enumeration<String> urlArgs, String url) {
		JSONObject urlArgsJson = new JSONObject();
		try {
			if (urlArgs != null) {
				while (urlArgs.hasMoreElements()) {
					try {
						String paraName = (String) urlArgs.nextElement();
						urlArgsJson.put(paraName, request.getParameter(paraName));
					} catch (Exception e) {
						log.error("=============记录url中的参数出错", url);
						break;
					}
				}
			}
		} catch (Exception e) {
			log.error("=============记录url中的参数出错, " + url);
		}
		return urlArgsJson;
	}

rex.tan committed
205 206 207 208 209 210
	private static String now2String() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		Date now = new Date();
		return sdf.format(now);
	}
rex.tan committed
211
}