log4j.properties
# 设置root logger等级为ALL,且appender有A1和FILE
log4j.rootLogger=ALL, A2
# 设置个控制台输出源,该appender名叫:A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#设置个文件输出源,该appender名叫:FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=D:/logs/log4j.log
log4j.appender.FILE.append=true
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
#设置个文件输出源(滚动文件输出源,按照文件大小重新生成临时文件),该appender名叫:A2
log4j.appender.A2=org.apache.log4j.RollingFileAppender
log4j.appender.A2.file=D:/logs/log4j.log
log4j.appender.A2.append=true
#maxFileSize 文件最大大小,单位是:【KB】超过会将旧的数据放在临时文件,新的日志继续打印在file指定的文件名中
log4j.appender.A2.maxFileSize=1
#maxBackupIndex 文件最大备份数,默认为1
log4j.appender.A2.maxBackupIndex=10
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
测试代码
package com.example.test;
import java.io.PrintWriter;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.Test;
public class TestLog4j {
private static final Logger logger = Logger.getLogger(TestLog4j.class);
@Test
public void testFile() {
while (true) {
logger.fatal("fatal");
}
}
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/02923a1dce7f4086a5567da0a9899f7e.png)