package com.himo.Filter;
import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
/**
* 作者:修罗大人
* 时间:2018-11-15 16:46
* 描述:日志过滤器
*/
@Component
@WebFilter(filterName ="logFilter", urlPatterns ="/*")
public class LogFilterimplements Filter {
private Loggerlogger = LoggerFactory.getLogger(this.getClass());
private static final StringignoreUrlRegex =".*((pay/)|(/index)|(/index/.*)|([.]((html)|(jsp)|(css)|(js)|(gif)|(png))))$";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
ThreadContext.put("TId", UUID.randomUUID().toString());
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
// 请求html页面、js不打印日志
if (httpServletRequest.getRequestURI().matches(ignoreUrlRegex)) {
ThreadContext.clearAll();
filterChain.doFilter(servletRequest,servletResponse);
return;
}
HttpServletRequest request = (HttpServletRequest) servletRequest;
logger.info("url: " + request.getRequestURL());//url
logger.info("ip: " + request.getRemoteHost());//ip
logger.info("method: "+request.getMethod());//post or get? or ?
Map parameterMap = request.getParameterMap();
logger.warn("请求url参数:" + JSON.toJSONString(parameterMap));
try {
ServletInputStream inputStream = request.getInputStream();
int len = request.getContentLength();
if (len >0)
{
byte[] bytes =new byte[len];
int i =0;
ByteArrayOutputStream bo =new ByteArrayOutputStream();
inputStream.read(bytes,i,len);
bo.write(bytes,i,len);
bo.flush();
bo.close();
String result = bo.toString();
logger.warn("请求体参数" + result);
}
}catch (IOException e) {
e.printStackTrace();
}
HttpServletResponse resp = (HttpServletResponse) servletResponse;
ResponseWrapper mResp =new ResponseWrapper(resp);// 包装响应对象 resp 并缓存响应数据
filterChain.doFilter(request, mResp);
byte[] bytes = mResp.getBytes();// 获取缓存的响应数据
if (bytes.length >0)
{
String responseStr =new String(bytes);
logger.warn("返回值:" + responseStr);
}
// System.out.println("压缩前大小:" + bytes.length);
// System.out.println("压缩前数据:" + new String(bytes,"utf-8"));
// ByteArrayOutputStream bout = new ByteArrayOutputStream();
// GZIPOutputStream gzipOut = new GZIPOutputStream(bout); // 创建 GZIPOutputStream 对象
// gzipOut.write(bytes); // 将响应的数据写到 Gzip 压缩流中
// gzipOut.flush();
// gzipOut.close(); // 将数据刷新到 bout 字节流数组
// byte[] bts = bout.toByteArray();
// System.out.println("压缩后大小:" + bts.length);
// resp.setHeader("Content-Encoding", "gzip"); // 设置响应头信息
// resp.getOutputStream().write(bts); // 将压缩数据响应给客户端
}
@Override
public void init(FilterConfig filterConfig)throws ServletException {
}
@Override
public void destroy() {
}
}
package com.himo.Filter;
/**
* 作者:修罗大人
* 时间:2018-11-15 17:13
* 描述:ResponseWrapper
*/
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
public class ResponseWrapperextends HttpServletResponseWrapper {
private ByteArrayOutputStreambytes =new ByteArrayOutputStream();
private HttpServletResponseresponse;
private PrintWriterpwrite;
public ResponseWrapper(HttpServletResponse response) {
super(response);
this.response = response;
}
@Override
public ServletOutputStream getOutputStream()throws IOException {
return new MyServletOutputStream(bytes);// 将数据写到 byte 中
}
/**
* 重写父类的 getWriter () 方法,将响应数据缓存在 PrintWriter 中
*/
@Override
public PrintWriter getWriter()throws IOException {
try {
pwrite =new PrintWriter(new OutputStreamWriter(bytes,"utf-8"));
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return pwrite;
}
/**
* 获取缓存在 PrintWriter 中的响应数据
*
* @return
*/
public byte[] getBytes() {
if (null !=pwrite) {
pwrite.close();
return bytes.toByteArray();
}
if (null !=bytes) {
try {
bytes.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
return bytes.toByteArray();
}
class MyServletOutputStreamextends ServletOutputStream {
private ByteArrayOutputStreamostream;
public MyServletOutputStream(ByteArrayOutputStream ostream) {
this.ostream = ostream;
}
@Override
public void write(int b)throws IOException {
ostream.write(b);// 将数据写到 stream 中
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
}
}
网友评论