通过过滤器来实现web应用的log4j打印自定义信息
log4j配置文件
log4j.rootCategory=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{HH:mm:ss.SSS}] %p [b]%X{ip} %X{userName}[/b] %c{1}.%M(%L) | %m%n
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{
@Override
public 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");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public void destroy() {
}
}
log4j配置文件
log4j.rootCategory=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{HH:mm:ss.SSS}] %p [b]%X{ip} %X{userName}[/b] %c{1}.%M(%L) | %m%n
[15:27:52.682] DEBUG 127.0.0.1 admin SimpleTest.testLog(42) | testLog