001/* 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v2.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014 015package ch.qos.logback.core.rolling.helper; 016 017import ch.qos.logback.core.status.ErrorStatus; 018import ch.qos.logback.core.status.WarnStatus; 019 020import java.io.File; 021import java.io.FileInputStream; 022import java.io.FileOutputStream; 023import java.util.zip.GZIPOutputStream; 024 025import static ch.qos.logback.core.rolling.helper.CompressionMode.GZ_SUFFIX; 026 027public class GZCompressionStrategy extends CompressionStrategyBase { 028 029 030 @Override 031 public void compress(String originalFileName, String compressedFileName, String innerEntryName) { 032 033 File file2gz = new File(originalFileName); 034 035 if (!file2gz.exists()) { 036 addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this)); 037 038 return; 039 } 040 041 if (!compressedFileName.endsWith(GZ_SUFFIX)) { 042 compressedFileName = compressedFileName + GZ_SUFFIX; 043 } 044 045 File gzedFile = new File(compressedFileName); 046 047 if (gzedFile.exists()) { 048 addWarn("The target compressed file named [" + compressedFileName + "] exist already. Aborting file compression."); 049 return; 050 } 051 052 addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]"); 053 createMissingTargetDirsIfNecessary(gzedFile); 054 boolean compressionSucceeded = false; 055 try (FileInputStream fis = new FileInputStream(originalFileName); 056 GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(compressedFileName), BUFFER_SIZE)) { 057 058 byte[] inbuf = new byte[BUFFER_SIZE]; 059 int n; 060 061 while ((n = fis.read(inbuf)) != -1) { 062 gzos.write(inbuf, 0, n); 063 } 064 065 compressionSucceeded = true; 066 addInfo("Done GZ compressing [" + file2gz + "] as [" + gzedFile + "]"); 067 } catch (Exception e) { 068 addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e)); 069 } 070 071 072 // Delete the original only after successful compression so a failure leaves it intact. 073 if (compressionSucceeded) { 074 if (!file2gz.delete()) { 075 addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this)); 076 } 077 } else { 078 addStatus(new WarnStatus("Compression of [" + originalFileName + "] failed. Original file left intact.", this)); 079 } 080 081 } 082 083}