log4j和common-logging结合使用

Posted on 2006-07-06 17:31 负人博客 阅读(2914) 评论(0)  编辑  收藏 所属分类: 开源研究
     在我们的日常开发中,经常需要通过输出一些信息进行程序的调试,如果到处都用system.out.println()则在项目发布之后要逐一删除,而log4j提供了一种新的调试输出机制以解决输出的问题。log4j的原理是使用一个配置文件log4j.properties进行管理,在调试的时候可以把输出级别调低,项目正式发布之后把级别调高,这样以前的一些输出就可以屏蔽了,不用到程序当中再进行逐一删除。关于log4j的介绍网上很多,随便google一下就可以顺利的使用log4j了。在这里介绍一下log4j和common-logging的联合使用,因为在很多框架当中都是结合了common-logging和log4j的应用。像spring之类的框架里面存在很多debug输出,用common-logging可以很容易的打印输出,以用于了解spring的运行机制!
   使用介绍:
   1.下载jar包:
       log4j-1.2.9.jar和commons-logging.jar
   2.在web目录的classes下面添加两个文件:commons-logging.properties和log4j.properties      
      log4j.properties(例子):
          ##LOGGERS##
          #define a logger
          log4j.rootLogger=INFO,console,file
          #log4j.rootLogger=DEBUG,console,file
          ##APPENDERS##
         #define an appender named console,which is set to be a ConsoleAppender
         log4j.appender.console=org.apache.log4j.ConsoleAppender
         #define an appender named file,which is set to be a RollingFileAppender
         log4j.appender.file=org.apache.log4j.RollingFileAppender
         log4j.appender.file.File=log-wst.txt
         ##LAYOUTS##
         #assign a SimpleLayout to console appender
         log4j.appender.console.layout=org.apache.log4j.SimpleLayout
         #assign a PatternLayout to file appender
         log4j.appender.file.layout=org.apache.log4j.PatternLayout
         log4j.appender.file.layout.ConversionPattern=%p - %m%n
     
      commons-logging.properties(例子)
          ##
          org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JCategoryLog
   3.应用实例:
     package com.wes.test;
     import org.apache.commons.logging.Log;
     import org.apache.commons.logging.LogFactory;
    public abstract class BaseClass{
         /** 用于日志输出 */
         protected Log log = LogFactory.getLog(this.getClass());
    }
    这样在子类中可以直接调用log输出即可:
   public class DerivedClass extends BaseClass {
         pulbic void test() {
             //如果log4j.properties文件配置的级别<=info则可以正常输出(info/debug) 
            log.info("这是info级别的输出");   
             //如果log4j.properties文件的级别为debug则可以正常输出(debug) 
            log.debug("这是debug级别的输出");
         }
   }

 


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 26, comments - 5, trackbacks - 0, articles - 8

Copyright © 负人博客