Log4j(1.2.17) - hello world

1. Maven 依赖

<dependencies>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

2. 配置 log4j.properties

log4j.rootLogger = warn, STDOUT, DEBUG, ERROR

## Console
log4j.appender.STDOUT = org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.Target = System.out
log4j.appender.STDOUT.layout = org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern =  %d{ABSOLUTE} %5p [%t] (%F:%L) - %m%n

## DEBUG
log4j.appender.DEBUG = org.apache.log4j.DailyRollingFileAppender
log4j.appender.DEBUG.File = log/debug.log
log4j.appender.DEBUG.DatePattern='.'yyyy-MM-dd
log4j.appender.DEBUG.Append = true
log4j.appender.DEBUG.Threshold = DEBUG
log4j.appender.DEBUG.layout = org.apache.log4j.PatternLayout
log4j.appender.DEBUG.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} %5p [%t] (%F:%L) - %m%n

## ERROR
log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERROR.File = log/error.log
log4j.appender.ERROR.DatePattern='.'yyyy-MM-dd
log4j.appender.ERROR.Append = true
log4j.appender.ERROR.Threshold = ERROR 
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} %5p [%t] (%F\:%L) - %m%n

3. 测试

package com.huey.hello.log4j;

import org.apache.log4j.Logger;

public class Log4jTest {

    static final Logger LOGGER = Logger.getLogger(Log4jTest.class);

    public void doLog() {
        LOGGER.debug("Debug Info");
        LOGGER.info("Info Info");
        LOGGER.warn("Warn Info");
        LOGGER.error("Error Info");
        LOGGER.fatal("Fatal Info");
    }

    public static void main(String[] args) {
        Log4jTest test = new Log4jTest();
        test.doLog();
    }

}

4. 控制台输出,仅输出 WARN 级别及以上的日志

10:36:17,706  WARN [main] (Log4jTest.java:12) - Warn Info
10:36:17,708 ERROR [main] (Log4jTest.java:13) - Error Info
10:36:17,709 FATAL [main] (Log4jTest.java:14) - Fatal Info

5. debug.log,仅输出 WARN 级别及以上的日志

2015-12-29 10:36:17  WARN [main] (Log4jTest.java:12) - Warn Info
2015-12-29 10:36:17 ERROR [main] (Log4jTest.java:13) - Error Info
2015-12-29 10:36:17 FATAL [main] (Log4jTest.java:14) - Fatal Info

6. error.log,仅输出 ERROR 级别及以上的日志

2015-12-29 10:36:17 ERROR [main] (Log4jTest.java:13) - Error Info
2015-12-29 10:36:17 FATAL [main] (Log4jTest.java:14) - Fatal Info

 

posted on 2015-12-29 10:41  huey2672  阅读(754)  评论(0编辑  收藏  举报