情况是,多个进程使用相同的log4j.propery写入日志文件,但是当日志文件大小最大时。它需要滚动,所以这些过程会很混乱。我该如何解决。这是翻转Java代码。
public void rollOver() {
LogLog.debug("rolling over count=" + ((CountingQuietWriter) this.qw).getCount());
LogLog.debug("maxBackupIndex=" + this.maxBackupIndex);
if (this.maxBackupIndex > 0) {
File file = new File(this.fileName + '.' + this.maxBackupIndex);
if (file.exists()) {
file.delete();
}
File target;
for (int e = this.maxBackupIndex - 1; e >= 1; --e) {
file = new File(this.fileName + "." + e);
if (file.exists()) {
target = new File(this.fileName + '.' + (e + 1));
LogLog.debug("Renaming file " + file + " to " + target);
file.renameTo(target);
}
}
target = new File(this.fileName + "." + 1);
this.closeFile();
file = new File(this.fileName);
LogLog.debug("Renaming file " + file + " to " + target);
file.renameTo(target);
}
try {
this.setFile(this.fileName, false, this.bufferedIO, this.bufferSize);
} catch (IOException arg3) {
LogLog.error("setFile(" + this.fileName + ", false) call failed.", arg3);
}
}
我做了一个实验。启动2个JVM记录文件。他们使用相同的log4j附加程序记录内容并登录到同一文件。
import java.io.IOException;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
public class LogMain {
public static void main(String[] args) {
Logger logger;
try {
Layout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss,SSS}][%p][%C][Line:%L][%t] %m%n");
RollingFileAppender appender = new RollingFileAppender(layout, "D://log/test.log");
appender.setName("monitor_log");
appender.setMaxFileSize("1MB");
appender.setMaxBackupIndex(100);
appender.setEncoding("UTF-8");
logger = Logger.getLogger("MONITOR_LOG");
logger.removeAllAppenders();
logger.setAdditivity(false);
logger.addAppender(appender);
logger.setLevel(Level.INFO);
} catch (IOException e) {
throw new RuntimeException(e);
}
int i = 0;
while (i < 100000) {
logger.error(i);
i++;
}
System.out.println("success");
}
}
然后我在两个Windows cmd中启动此Java代码。
java -cp .;D:\tts9\tts9\workspace\LogHandle\log4j-1.2.8.jar LogMain
,并且日志文件完全混乱。 enter image description here