前言
生产碰到了一个日志压缩了, 但原文件没有被删除的问题
排查
在查找了logback源码后可以确定 , 源码里在压缩完后是进行了删除操作的
private void zipCompress(String nameOfFile2zip, String nameOfZippedFile, String innerEntryName) {
File file2zip = new File(nameOfFile2zip);
if (!file2zip.exists()) {
addStatus(new WarnStatus("The file to compress named [" + nameOfFile2zip
+ "] does not exist.", this));
return;
}
if (innerEntryName == null) {
addStatus(new WarnStatus("The innerEntryName parameter cannot be null", this));
return;
}
if (!nameOfZippedFile.endsWith(".zip")) {
nameOfZippedFile = nameOfZippedFile + ".zip";
}
File zippedFile = new File(nameOfZippedFile);
if (zippedFile.exists()) {
addStatus(new WarnStatus("The target compressed file named ["
+ nameOfZippedFile + "] exist already.", this));
return;
}
addInfo("ZIP compressing [" + file2zip + "] as ["+zippedFile+"]");
createMissingTargetDirsIfNecessary(zippedFile);
BufferedInputStream bis = null;
ZipOutputStream zos = null;
try {
bis = new BufferedInputStream(new FileInputStream(nameOfFile2zip));
zos = new ZipOutputStream(new FileOutputStream(nameOfZippedFile));
ZipEntry zipEntry = computeZipEntry(innerEntryName);
zos.putNextEntry(zipEntry);
byte[] inbuf = new byte[BUFFER_SIZE];
int n;
while ((n = bis.read(inbuf)) != -1) {
zos.write(inbuf, 0, n);
}
bis.close();
bis = null;
zos.close();
zos = null;
if (!file2zip.delete()) {
addStatus(new WarnStatus("Could not delete [" + nameOfFile2zip + "].",
this));
}
} catch (Exception e) {
addStatus(new ErrorStatus("Error occurred while compressing ["
+ nameOfFile2zip + "] into [" + nameOfZippedFile + "].", this, e));
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// ignore
}
}
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
// ignore
}
}
}
}
这个压缩方法方法是在ch.qos.logback.core.rolling.helper.Compressor 类中, 这个方法是 入参有三个:
nameOfFile2zip: 源文件全名路径 nameOfZippedFile: 压缩包的全名路径 innerEntryName: 文件被压缩在压缩包中的文件名称
那么既然压缩后会进行删除 , 为啥已经压缩完成了 , 但没被删除呢?
原因只能是在要删除源文件的时候无法被删除 , 正被某些操作或程序占用着 , 或者是权限问题.
结果
最后排查下logback的配置 , 发现info warn error三个级别的日志都输出到同一个文件里了,
然后把warn 和 error级别的注释掉 , 压缩就正常了.
估计是每个级别的日志的处理通道或队列不一样, 压缩是只阻塞当前的 , 别的还会继续打印,
这只是自己的判断, 因为解决了问题就没深究源码找原因是否是这样.
最后是更改了各个级别日志的输出方式.