log4j显示ip或用户名等自定义信息
通过过滤器来实现web应用的log4j打印自定义信息
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 javax.servlet.http.HttpServletRequest;import org.apache.log4j.MDC;public class Log4jFilter implements Filter{@Overridepublic void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {String ip = req.getRemoteAddr();String userName = (String)((HttpServletRequest)req).getSession().getAttribute("userName");//获取用户名MDC.put("ip", ip);MDC.put("userName", userName);chain.doFilter(req, res);MDC.remove("ip");MDC.remove("userName");}@Overridepublic void init(FilterConfig arg0) throws ServletException {}@Overridepublic void destroy() {}}
[15:27:52.682] DEBUG 127.0.0.1 admin SimpleTest.testLog(42) | testLog