log4j自定义输出级别和输出信息
相关文章链接:
我们定义一个CUSTOMLOG1级别,自定义输出信息为访问者ip和属性attr。
1.在web.xml中添加一个过滤器
<!-- 日志过滤器 -->
<filter>
<filter-name>Log4jFilter</filter-name>
<filter-class>cn.com.mydemo.interceptor.Log4jFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Log4jFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.过滤器Log4jFilter.java
package cn.com.mydemo.interceptor;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.MDC;
/**
* @Description 日志过滤器
* @author jjy
* @create 2019-06-19
*/
public class Log4jFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//获取访问者ip
String ip = request.getRemoteAddr();
//log4j通过访问MDC中存入的键值对获取自定义属性,写法为%X{ip}(ip为MDC放入的key)
MDC.put("ip", ip);
try {
chain.doFilter(request, response);
} catch (Exception e) {
e.printStackTrace();
}
//清空MDC
if(MDC.getContext() != null) {
MDC.getContext().clear();
}