How to initialize log4j properly?

前端 未结 24 3027
太阳男子
太阳男子 2020-11-22 06:49

After adding log4j to my application I get the following output every time I execute my application:

log4j:WARN No appenders could be found for logger (slideselec         


        
24条回答
  •  孤街浪徒
    2020-11-22 07:05

    Another way to do it without putting the property file on the classpath, is to set the property from the java code directly. Here is the sample code.

    public class Log4JSample {
    
    public static void main(String[] args) {
        Properties properties=new Properties();
        properties.setProperty("log4j.rootLogger","TRACE,stdout,MyFile");
        properties.setProperty("log4j.rootCategory","TRACE");
    
        properties.setProperty("log4j.appender.stdout",     "org.apache.log4j.ConsoleAppender");
        properties.setProperty("log4j.appender.stdout.layout",  "org.apache.log4j.PatternLayout");
        properties.setProperty("log4j.appender.stdout.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");
    
        properties.setProperty("log4j.appender.MyFile", "org.apache.log4j.RollingFileAppender");
        properties.setProperty("log4j.appender.MyFile.File", "my_example.log");
        properties.setProperty("log4j.appender.MyFile.MaxFileSize", "100KB");
        properties.setProperty("log4j.appender.MyFile.MaxBackupIndex", "1");
        properties.setProperty("log4j.appender.MyFile.layout",  "org.apache.log4j.PatternLayout");
        properties.setProperty("log4j.appender.MyFile.layout.ConversionPattern","%d{yyyy/MM/dd HH:mm:ss.SSS} [%5p] %t (%F) - %m%n");
    
        PropertyConfigurator.configure(properties);
    
        Logger logger = Logger.getLogger("MyFile");
    
        logger.fatal("This is a FATAL message.");
        logger.error("This is an ERROR message.");
        logger.warn("This is a WARN message.");
        logger.info("This is an INFO message.");
        logger.debug("This is a DEBUG message.");
        logger.trace("This is a TRACE message.");
    }
    

    }

提交回复
热议问题