云开 发表于 2009-2-9 09:47:39

Apusic

常碰到项目中用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文件就可以改变了。
页: [1]
查看完整版本: Apusic