Chinaunix首页 | 论坛 | 博客
  • 博客访问: 543559
  • 博文数量: 855
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-16 19:08
文章分类

全部博文(855)

文章存档

2011年(1)

2008年(854)

我的朋友

分类:

2008-10-16 19:19:04

常碰到项目中用Log4J,但是自己一直都没有认真去研究过Log4J的运行流程,看了许多资料讲得都是Log4J.properties怎么配置,但是Log4J启动→调用→输出的流程仍然不清楚,本文就准备对Log4J的详细启动过程进行介绍,使得大家可以更好的在Apusic中使用Log4J。

        1. 编写一个Servlet程序,目标是初始化Log4J的相关配置,具体内容参考附件中的Log4jInit.java程序,附件地址: 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应用中的代码使用

        2. 配置web.xml文件,对Log4jInit在Web应用加载过程中初始化

            log4j-init   wombat.Log4jInit

              log4j-init-file    WEB-INF/classes/log4j.properties      1 

        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文件就可以改变了。

【责编:landy】

--------------------next---------------------

阅读(196) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~