2010-11-12 32 views
0

现在我正在学习log4j,请指导我如何逐步创建和运行简单示例。如何创建log4j文件并运行程序

+0

你可能在错误地看问题,log4j网站有足够的例子开始使用。请查看http://logging.apache.org/log4j/和http://logging.apache.org/log4j/1.2/manual.html – dvhh 2010-11-12 10:31:01

回答

1
+0

-1,本手册非常详细且过于复杂。此外,a)如果他找到了一个简单的例子,他就不会问这个问题,并且b)这是谷歌最初的“创建log4j文件”命中之一。 – JaneGoodall 2015-05-26 19:24:24

3

Log4J Java - A simple Log4J example

package com.devdaily.log4jdemo; 

import org.apache.log4j.Category; 
import org.apache.log4j.PropertyConfigurator; 
import java.util.Properties; 
import java.io.FileInputStream; 
import java.io.IOException; 

/** 
* A simple Java Log4j example class. 
* @author alvin alexander, devdaily.com 
*/ 
public class Log4JExample 
{ 
    // our log4j category reference 
    static final Category log = Category.getInstance(Log4JDemo.class); 
    static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties"; 

    public static void main(String[] args) 
    { 
    // call our constructor 
    new Log4JExample(); 

    // Log4J is now loaded; try it 
    log.info("leaving the main method of Log4JDemo"); 
    } 

    public Log4JExample() 
    { 
    initializeLogger(); 
    log.info("Log4JExample - leaving the constructor ..."); 
    } 

    private void initializeLogger() 
    { 
    Properties logProperties = new Properties(); 

    try 
    { 
     // load our log4j properties/configuration file 
     logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE)); 
     PropertyConfigurator.configure(logProperties); 
     log.info("Logging initialized."); 
    } 
    catch(IOException e) 
    { 
     throw new RuntimeException("Unable to load logging property " + 
            LOG_PROPERTIES_FILE); 
    } 
    } 
}