springboot 拦截器记录每次请求的参数到数据库或者指定文件(文件每天生成一次)

package com.publichealth.common.interceptor;


import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import com.publichealth.common.log.LogUtil;
import com.publichealth.common.utils.DateUtils;
import com.publichealth.modules.service.ApiLogService;


/***
 * 拦截器
 * 
 * @author Stu
 *
 */
@Component
public class TimeCostInterceptor implements HandlerInterceptor {


// 注意此处的Service注入:需要对拦截器做一个有参数构造方法,然后再MyWebAppConfigurer里面注入Service并传入参数
// 不能直接注入,因为拦截器是优先于spring对于Bean的加载的
private ApiLogService apiLogService;


private final static Logger log = LoggerFactory.getLogger(TimeCostInterceptor.class);


public TimeCostInterceptor(ApiLogService apiLogService) {
this.apiLogService = apiLogService;
}


// 获取当前客户端请求参数
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// // 把参数存入数据库
// ApiLog apiLog = new ApiLog();
// long startTime = System.currentTimeMillis();
// request.setAttribute("startTime", startTime);
//
// // 判断请求方式是post还是get
// String method = request.getMethod();
//
// apiLog.setIpVal(getIpAddress(request));
// apiLog.setServerCreatetime(DateUtils.dateToString(new Date()));
// apiLog.setMethod(method);
// // 1:安卓平板,2:安卓手机,3:ios手机
// String sourceTypeString[] =
// request.getParameterMap().get("equipmentType");
// if (sourceTypeString != null && sourceTypeString.length > 0) {
// apiLog.setSourceType(sourceTypeString[0]);
// }
//
// // 序列号
// String appidString[] = request.getParameterMap().get("serialNumber");
// if (appidString != null && appidString.length > 0) {
// apiLog.setAppid(appidString[0]);
// }
//
// // 软件版本号
// String softVersionS[] = request.getParameterMap().get("version");
// if (softVersionS != null && softVersionS.length > 0) {
// apiLog.setSoftVersion(softVersionS[0]);
// }
//
// if (method != null && method.equals("GET")) {
// // get请求
// apiLog.setFullpath(
// request.getLocalName() + request.getRequestURI() +
// getParamStringToGet(request.getParameterMap()));
// apiLog.setParameter(getParamStringToGet(request.getParameterMap()));
// } else {
// // post 请求
// apiLog.setFullpath(request.getLocalName() + request.getRequestURI());
// apiLog.setParameter(getParamStringToGet(request.getParameterMap()));
// }
// apiLogService.save(apiLog);


// 把日志存入文件夹
StringBuffer buffer = new StringBuffer();
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);


// 判断请求方式是post还是get
String method = request.getMethod();
buffer.append("当前请求方法:==>" + method);
// 换行
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求ip:==>" + getIpAddress(request));
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求时间:==>" + DateUtils.dateToString(new Date()));
// 1:安卓平板,2:安卓手机,3:ios手机
String sourceTypeString[] = request.getParameterMap().get("equipmentType");
if (sourceTypeString != null && sourceTypeString.length > 0) {
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求终端:==>" + sourceTypeString[0]);


}


// 序列号
String appidString[] = request.getParameterMap().get("serialNumber");
if (appidString != null && appidString.length > 0) {
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求pad序列号:==>" + appidString[0]);
}


// 软件版本号
String softVersionS[] = request.getParameterMap().get("version");
if (softVersionS != null && softVersionS.length > 0) {
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求软件版本号:==>" + softVersionS[0]);
}
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求路径:==>" + request.getLocalName() + request.getRequestURI());
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求参数:==>" + getParamStringToGet(request.getParameterMap()));


// 下面是重点判断请求参数是否带有图片参数
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = multipartRequest.getFileMap();
if (files != null && files.size() > 0) {
// 当前请求带有图片
buffer.append(System.getProperty("line.separator"));
buffer.append("当前请求带有图片参数,一共有:==>" + files.size() + "张图片");
}
}
// 写入日志文件
LogUtil.writeLog(buffer.toString());


log.info("当前请求路径:==>" + request.getLocalName() + request.getRequestURI());
log.info("当前请求参数:==>" + getParamStringToGet(request.getParameterMap()));


return true;
}


public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
long startTime = (Long) request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
long executeTime = endTime - startTime;
if (handler instanceof HandlerMethod) {
StringBuilder sb = new StringBuilder(1000);
sb.append("CostTime  : ").append(executeTime).append("ms").append("\n");
sb.append("-------------------------------------------------------------------------------");
System.out.println(sb.toString());
}
}


/***
* get 请求

* @param map
*            参数
* @return
*/
private String getParamStringToGet(Map<String, String[]> map) {
StringBuilder sb = new StringBuilder();
for (Entry<String, String[]> e : map.entrySet()) {
sb.append(e.getKey()).append("=");
String[] value = e.getValue();
if (value != null && value.length == 1) {
sb.append(value[0]).append("&");
} else {
sb.append(Arrays.toString(value)).append("\t");
}
}
if (sb.length() > 0) {
// 去除最后一个&号
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}


public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {


}


// 获取真实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;
}

}



package com.publichealth.common.log;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.publichealth.common.utils.DateUtils;


/***
 * 每天生成一个日志文件 把每次的请求参数添加到日志文件夹
 * 
 * @author lixin
 *
 */
public class LogUtil {


private final static Logger log = LoggerFactory.getLogger(LogUtil.class);


// 获取操作系统
private static String OS = System.getProperty("os.name").toLowerCase();


// 文件夹windows
private static String filePathToWindows = "D:/logs/";
// linux
private static String filePathToLinux = "/home/logs/";


/***
* 往定时器创建的文件夹写入日志

* @param content
*            要写入的内容
*/
public static void writeLog(String content) {


File file = null;
String date = DateUtils.format(new Date());
// 判定操作系统
if (OS.indexOf("linux") >= 0) {
file = new File(filePathToLinux);
file.mkdir();
file = new File(filePathToLinux + date + ".txt");
} else if (OS.indexOf("windows") >= 0) {
file = new File(filePathToWindows);
file.mkdir();
file = new File(filePathToWindows + date + ".txt");
}
try {
// 如果文件不存在,则创建新的文件
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
log.error("第一次生成文件失败--------------------------------------------------");
}
try {
// 每次往文本末尾追加数据
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
writer.write("##############################开始 H模块:" + DateUtils.dateToString(new Date())
+ "##################################");
writer.newLine();
writer.write("当前方法进入时间:==>" + DateUtils.dateToString(new Date()));
writer.newLine();
writer.write(content);
writer.newLine();
writer.write(
"###########################################结束###############################################");
writer.newLine();
writer.newLine();
writer.close();
} catch (Exception e) {
e.printStackTrace();
log.error("拦截器写入日志失败------------------------------------------------------------");
}


}


}













阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭