經常碰到項目中用Log4J,但是自己一直都沒有認真去研究過Log4J的運行流程,看了許多資料講得都是Log4J.properties怎么配置,但是Log4J啟動→調用→輸出的流程仍然不清楚,本文就準備對Log4J的詳細啟動過程進行介紹,使得大家可以更好的在Apusic中使用Log4J。
?
1. 編寫一個Servlet程序,目標是初始化Log4J的相關配置,具體內容參考附件中的Log4jInit.java程序,附件下載地址:http://zhuyuanxiang.javaeye.com/topics/download/66d599d6-b21c-3933-a707-be2b08505519
public class Log4jInit extends HttpServlet {
?public void init() {
??ServletContext context = getServletConfig().getServletContext();
??Hierarchy hierarchy = new Hierarchy(new RootCategory(Level.DEBUG));
??// 將hierarchy初始化后保存到context中,在Web應用的全局供其他Web代碼使用。
??context.setAttribute("hierarchy", hierarchy);
??String prefix = getServletContext().getRealPath("/");
??String file = getInitParameter("log4j-init-file");
??// if the log4j-init-file is not set, then no point in trying
??if (file != null) {???// 增加hierarchy配置的內容
???new PropertyConfigurator().doConfigure(prefix + file, hierarchy);
???Logger logger = hierarchy.getLogger(Log4jInit.class.getName());
???logger.info("Logging initialized for Hello.");
??}
?}
關鍵就是對Hierachy的初始化,并且保存到context中,供其他Web應用中的Java代碼使用
2. 配置web.xml文件,對Log4jInit在Web應用加載過程中初始化
?<servlet>
??<servlet-name>log4j-init</servlet-name>
??<servlet-class>wombat.Log4jInit</servlet-class>
??<init-param>
???<param-name>log4j-init-file</param-name>
???<param-value>WEB-INF/classes/log4j.properties</param-value>
??</init-param>
??<load-on-startup>1</load-on-startup>
?</servlet>
3. 編寫HelloServlet.java,在代碼中使用Logger
?public void init() throws ServletException {
??ServletContext context = getServletConfig().getServletContext();
??// 從context中取出hierarchy供本Servlet的Logger使用
??Hierarchy hierarchy = (Hierarchy) context.getAttribute("hierarchy");
??if (hierarchy == null) {
???context.log("The Hello web-application is not properly intialized.");
??} else {
???logger = hierarchy.getLogger(HelloServlet.class.getName());
?? logger.info("HelloServlet initiation is OK!");
??}
?}
?
因此,如果使用Log4J需要在代碼中初始化Log4J的相關配置并保存到上下文中,同時配置信息寫在web.xml中,并且正確提供log4j.properties文件,然后在代碼中調用了Logger就可以輸出日志信息了。
本例子的/hello.log一般會輸出在應用所在盤的根目錄下,開發人員可以根據自己的需要調整Log4J.properties文件就可以改變了。