天天看點

使用commons-logging記錄日志資訊

Jakarta Commons Logging(JCL)是一個輕量級的日志工具,可以根據實際環境調用Log4J等具體日志實作工具。

下面介紹一下在Jboss環境中commons-logging的實際應用。

程式直接借用了OReilly的Enterprise JavaBeans Fourth中的4.2節的例子,增加了日志資訊的記錄功能。

首先實作了一個TestCommonsLogging類,需要用到commons-logging.jar:

package com.titan;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class TestCommonsLogging {

   private static Log log_ = LogFactory.getLog(TestCommonsLogging.class);

    private TestCommonsLogging() {

    }

    public static boolean isTraceEnabled() {

        return log_.isTraceEnabled();

    } 

    public static boolean isDebugEnabled() {

        return log_.isDebugEnabled();

    }

    public static boolean isInfoEnabled() {

        return log_.isInfoEnabled();

    }

    public static boolean isWarnEnabled() {

        return log_.isWarnEnabled();

    }

    public static boolean isErrorEnabled() {

        return log_.isErrorEnabled();

    }

    public static boolean isFatalEnabled() {

        return log_.isFatalEnabled();

    }

    // dump msg as is..

    public static void logTrace(String message) {

        log_.trace(message);

    }   

    public static void logDebug(String message) {

        log_.debug(message);

    }   

    public static void logInfo(String message) {

        log_.info(message);

    }

    public static void logWarning(String message) {

        log_.warn(message);

    }   

    public static void logError(String message) {

     log_.error(message);

    } 

    public static void logFatal(String message) {

        log_.fatal(message);

    }   

}

然後,在TravelAgentBean.java中調用TestCommonsLogging,實作日志資訊的記錄:

   public String [] listCabins(int shipID, int bedCount)

   {

     //.......

     if (TestCommonsLogging.isTraceEnabled())

     TestCommonsLogging.logTrace("trace log!!!");

    if (TestCommonsLogging.isDebugEnabled())

     TestCommonsLogging.logDebug("debug log!!!");

    if (TestCommonsLogging.isInfoEnabled())

     TestCommonsLogging.logInfo("info log!!!");

    if (TestCommonsLogging.isWarnEnabled())

     TestCommonsLogging.logWarning("warning log!!!");

    if (TestCommonsLogging.isErrorEnabled())

     TestCommonsLogging.logError("error log!!!");

    if (TestCommonsLogging.isFatalEnabled())

     TestCommonsLogging.logFatal("fatal log!!!");

    //.........

  }

最後,設定%JBOSS_HOME%/server/default/conf/log4j.xml,增加:

  <!--Limit com.titan log level-->

  <category name="com.titan">

    <priority value="ERROR"/>

  </category>

value可設定為TRACE,DEBUG,INFO,WARNING,ERROR,FATAL.

在Jboss中運作程式,顯示日志:

  2007-05-02 15:58:04,765 ERROR [com.titan.TestCommonsLogging] error log!!!

  2007-05-02 15:58:04,765 FATAL [com.titan.TestCommonsLogging] fatal log!!!

參考資料:

  1. JCL官方網站:http://jakarta.apache.org/commons/logging/

  2. OReilly Enterprise JavaBeans Fourth Edition