Log4j 基本配置示例

1.log4j.properties

log4j.rootLogger=INFO, stdout, fileout
log4j.logger.TestProject=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %l %c : %m%n
log4j.appender.fileout=org.apache.log4j.FileAppender
log4j.appender.fileout.File=c:/test.log
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %l %c : %m%n

2.Log类

import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log {

    private static Logger logger;

    private static String filePath = "config/log4j.properties";

    private static boolean flag = false;

    private static synchronized void getPropertyFile() {
        logger = Logger.getLogger("TestProject");
        PropertyConfigurator.configure(new File(filePath).getAbsolutePath());
        flag = true;
    }

    private static void getFlag() {
        if (flag == false)
            Log.getPropertyFile();
    }

    public static void logInfo(String message) {
        Log.getFlag();
        logger.info(message);
    }

    public static void logError(String message) {
        Log.getFlag();
        logger.error(message);
    }

    public static void logWarn(String message) {
        Log.getFlag();
        logger.warn(message);
    }

}

 

posted on 2013-09-11 11:51  张飞_  阅读(837)  评论(0编辑  收藏  举报

导航