Log4j容器初始化探究(5)

ServletDemo代码:

public class Log4jServletDemo extends HttpServlet { public static final Logger LOGGER = Logger.getLogger(Log4jServletDemo.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { service(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ service(req, resp); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ LOGGER.debug("Log4jServletDemo Info Level"); LOGGER.info("Log4jServletDemo Info Level"); LOGGER.warn("Log4jServletDemo Info Level"); LOGGER.error("Log4jServletDemo Info Level"); req.getRequestDispatcher("/index.jsp").forward(req, resp); } }

web.xml中配置:

<servlet> <servlet-name>servletDemo</servlet-name> <servlet-class>com.log.log4j.web.Log4jServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletDemo</servlet-name> <url-pattern>/demo</url-pattern> </servlet-mapping> 2.2 log4jweb初始化

初始化时序图:

Log4j容器初始化探究

初始化流程:

1.tomcat容器加载Log4jConfigListener

2.Log4jConfigListener把初始化Log4j的工作为委托给Log4jWebConfigurer

3.Log4jWebConfigurer获取配置文件路径。然后再委托给Log4jConfigurer

4.Log4jConfigurer调用Log4j框架的DomConfigurator.configure(url)或者PropertyConfigurator.configure(url)初始化配置Log4j,这样就走到了上面独立应用初始化Log4j的过程

2.3 源码探究 2.3.1 Log4jConfigListener

源码:

public class Log4jConfigListener implements ServletContextListener { @Override publicvoidcontextInitialized(ServletContextEvent event) { Log4jWebConfigurer.initLogging(event.getServletContext()); } @Override publicvoidcontextDestroyed(ServletContextEvent event) { Log4jWebConfigurer.shutdownLogging(event.getServletContext()); } }

源码流程解析:

1.调用contextInitialized(ServletContextEvent)初始化Log4j

2.委托给Log4jWebConfigurer初始化Log4j

2.3.2 Log4jWebConfigurer

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ef6d46734fd2100317cd4711a13b5bc1.html