使用场景:如需要进行性能调优,需要将执行时间单独输入到一个日志文件中
其中,log4j的配置
log4j.logger.console= DEBUG, test1
log4j.appender.test1=org.apache.log4j.FileAppender
log4j.appender.test1.File=D:/loginfo/console.log
log4j.appender.test1.layout=org.apache.log4j.PatternLayout
log4j.appender.test1.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.R1= DEBUG, test2
log4j.appender.test2=org.apache.log4j.FileAppender
log4j.appender.test2.File=D:/loginfo/R1.log
log4j.appender.test2.layout=org.apache.log4j.PatternLayout
log4j.appender.test2.layout.ConversionPattern=%d %p [%c] - %m%n
实例运行代码
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4JTest {
public static void main(String[] args) throws InterruptedException {
PropertyConfigurator.configure("log4j.properties");// 配置文件
Logger log = null;
Logger[] logs = { Logger.getLogger("console"), Logger.getLogger("R1")};
Random rand = new Random(System.currentTimeMillis());
while (true) {
log = logs[rand.nextInt(2)];
log.debug("debug!!!");
log.info("system info!!!");
log.warn("warn!!!");
log.error("error");
TimeUnit.SECONDS.sleep(2);
}
}
}
运行后产生的日志文件如图所示
参考的文献:
http://blog.csdn.net/wiwipetter/article/details/4390579
http://www.cnblogs.com/zdjlp/archive/2012/05/30/Log4j.html