001/* 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2025, 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 v1.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 025public class GZCompressionStrategy extends CompressionStrategyBase { 026 027 028 @Override 029 public void compress(String originalFileName, String compressedFileName, String innerEntryName) { 030 031 File file2gz = new File(originalFileName); 032 033 if (!file2gz.exists()) { 034 addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this)); 035 036 return; 037 } 038 039 if (!compressedFileName.endsWith(".gz")) { 040 compressedFileName = compressedFileName + ".gz"; 041 } 042 043 File gzedFile = new File(compressedFileName); 044 045 if (gzedFile.exists()) { 046 addWarn("The target compressed file named [" + compressedFileName + "] exist already. Aborting file compression."); 047 return; 048 } 049 050 addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]"); 051 createMissingTargetDirsIfNecessary(gzedFile); 052 try (FileInputStream fis = new FileInputStream(originalFileName); 053 GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(compressedFileName), BUFFER_SIZE)) { 054 055 byte[] inbuf = new byte[BUFFER_SIZE]; 056 int n; 057 058 while ((n = fis.read(inbuf)) != -1) { 059 gzos.write(inbuf, 0, n); 060 } 061 062 addInfo("Done GZ compressing [" + file2gz + "] as [" + gzedFile + "]"); 063 } catch (Exception e) { 064 addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e)); 065 } 066 067 if (!file2gz.delete()) { 068 addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this)); 069 } 070 } 071 072}