Commit c4b230cc authored by 耿迪迪's avatar 耿迪迪

日志写入本地文件 gengdidi

parent 458fd9fc
......@@ -20,6 +20,8 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
......@@ -38,6 +40,12 @@ public class LogInterceptor {
@Value("${secretKey}")
private String secretKey;
@Value("${isWriteLocal}")
private boolean isWriteLocal;
@Value("${fileUrl}")
private String fileUrl;
/**
* 定义拦截器规则
*/
......@@ -75,13 +83,25 @@ public class LogInterceptor {
}
/**
* 记录请求日志
* 根据配置记录请求日志
* @param params 请求参数
* @param result 请求结果
*/
private void insertRequestLogRecord(String params,String result) {
if(isWriteLocal){
writeToLocalFile(params,result);
}else {
writeToData(params,result);
}
}
/**
* 将请求日志写入数据库
* @param params 请求参数
* @param result 请求结果
*/
private void insertRequestLogRecord(String params,String result){
private void writeToData(String params,String result){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.getParameter("secretKey");
RequestLog requestLog = new RequestLog();
requestLog.setId(UUID.randomUUID().toString().replaceAll("-",""));
requestLog.setRequestMapping(request.getRequestURL().toString());
......@@ -91,4 +111,26 @@ public class LogInterceptor {
requestLog.setResult(JSONObject.toJSONString(result));
requestLogService.insert(requestLog);
}
/**
* 将请求日志写入本地文件
* @param params 请求参数
* @param result 请求结果
*/
private void writeToLocalFile(String params,String result) {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
FileWriter writer = new FileWriter(fileUrl,true);
writer.write("\n time:"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
writer.write(" requestMapping:"+request.getRequestURL().toString());
writer.write(" params:"+params);
writer.write(" postTime:"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
writer.write(" result:"+JSONObject.toJSONString(result));
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("写入本地文件出错:"+e);
}
}
}
......@@ -47,4 +47,8 @@ signNameJson: [\"泽宏云\"]
iPWhite: 192.168.2.23
#秘钥
secretKey: f225e66813e6d6a663daf919c1935dcb
\ No newline at end of file
secretKey: f225e66813e6d6a663daf919c1935dcb
#是否写入本地
isWriteLocal: false
fileUrl: E:\java\work\requireLog.text
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment