搜尋此網誌

2013年4月26日 星期五

Log4j的使用方式

以下是log4j的source code拿出來做解釋

MyLoggerFactory.java: 製作MyLogger物件實體的工廠類別.


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.Logger;  
 import org.apache.log4j.spi.LoggerFactory;  
 /**  
   A factory that makes new {@link MyLogger} objects.  
   See <b><a href="doc-files/MyLoggerFactory.java">source  
   code</a></b> for more details.  
   @author Ceki G&uuml;lc&uuml; */  
 public class MyLoggerFactory implements LoggerFactory {  
  /**  
    The constructor should be public as it will be called by  
    configurators in different packages. */  
  public  
  MyLoggerFactory() {  
  }  
  public  
  Logger makeNewLoggerInstance(String name) {  
   return new MyLogger(name);  
  }  
 }  

MyLogger.java: 在這裡定義每個 log level (warn, info , debug etc)想要印出的訊息.

以下這段程式碼是靜態的獨體模式(singleton design pattern)

private static MyLoggerFactory myFactory = new MyLoggerFactory();


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 /**  
   A simple example showing logger subclassing.   
   <p>See <b><a href="doc-files/MyLogger.java">source code</a></b>  
   for more details.  
   <p>See {@link MyLoggerTest} for a usage example.  
  */  
 public class MyLogger extends Logger {  
  // It's usually a good idea to add a dot suffix to the fully  
  // qualified class name. This makes caller localization to work  
  // properly even from classes that have almost the same fully  
  // qualified class name as MyLogger, e.g. MyLoggerTest.  
  static String FQCN = MyLogger.class.getName() + ".";  
  // It's enough to instantiate a factory once and for all.  
  private static MyLoggerFactory myFactory = new MyLoggerFactory();  
  /**  
    Just calls the parent constuctor.  
   */  
  public MyLogger(String name) {  
   super(name);  
  }  
  /**  
    Overrides the standard debug method by appending " world" at the  
    end of each message. */  
  public   
  void debug(Object message) {  
   super.log(FQCN, Level.DEBUG, message + " world.", null);    
  }  
  /**  
    This method overrides {@link Logger#getLogger} by supplying  
    its own factory type as a parameter.  
  */  
  public   
  static  
  Logger getLogger(String name) {  
   return Logger.getLogger(name, myFactory);   
  }  
  public  
  void trace(Object message) {  
   //super.log(FQCN, XLevel.TRACE, message, null);   
  }  
 }  

MyLoggerTest.java:

當不傳入任何參數的時候,使用預設的log設定, 並且在console輸出 (系統標準輸出介面)

或是傳入xml, properties設定檔, 套用裡面的設定值


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 import org.apache.log4j.xml.DOMConfigurator;  
 import org.apache.log4j.PropertyConfigurator;  
 import org.apache.log4j.helpers.LogLog;  
 /**  
   A simple example showing logger subclassing.   
   <p>The example should make it clear that subclasses follow the  
   hierarchy. You should also try running this example with a <a  
   href="doc-files/mycat.bad">bad</a> and <a  
   href="doc-files/mycat.good">good</a> configuration file samples.  
   <p>See <b><a  
   href="doc-files/MyLogger.java">source code</a></b> for more details.  
 */  
 public class MyLoggerTest {  
  /**  
    When called wihtout arguments, this program will just print   
    <pre>  
     DEBUG [main] some.cat - Hello world.  
    </pre>  
    and exit.  
    <b>However, it can be called with a configuration file in XML or  
    properties format.  
   */  
  static public void main(String[] args) {  
   if(args.length == 0) {  
    // Note that the appender is added to root but that the log  
    // request is made to an instance of MyLogger. The output still  
    // goes to System.out.  
    Logger root = Logger.getRootLogger();  
    Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");  
    root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));  
   }  
   else if(args.length == 1) {  
    if(args[0].endsWith("xml")) {  
      DOMConfigurator.configure(args[0]);  
    } else {  
      PropertyConfigurator.configure(args[0]);  
    }  
   } else {  
    usage("Incorrect number of parameters.");  
   }  
   try {  
    MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");    
    c.debug("Hello");  
   } catch(ClassCastException e) {  
    LogLog.error("Did you forget to set the factory in the config file?", e);  
   }  
  }  
  static  
  void usage(String errMsg) {  
   System.err.println(errMsg);  
   System.err.println("\nUsage: "+MyLogger.class.getName() + "[configFile]\n"  
         + " where *configFile* is an optional configuration file, "+  
               "either in properties or XML format.");  
   System.exit(1);  
  }  
 }