private static BufferedWriter createWriter(RotationConfig rotationConfig, Charset charset) { try { OutputStream outputStream = new RotatingFileOutputStream(rotationConfig); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, charset); return new BufferedWriter(outputStreamWriter); } catch (Exception error) { String message = String.format("failed opening file (file=%s, charset=%s)", rotationConfig.getFile(), charset); throw new RuntimeException(message, error); } }
private static void unsafeSyncCompress(File rotatedFile, File compressedFile) throws IOException { LOGGER.debug("compressing {rotatedFile={}, compressedFile={}}", rotatedFile, compressedFile); try (InputStream sourceStream = new FileInputStream(rotatedFile)) { try (OutputStream targetStream = new FileOutputStream(compressedFile)) { try (GZIPOutputStream gzipTargetStream = new GZIPOutputStream(targetStream)) { copy(sourceStream, gzipTargetStream); LOGGER.debug("deleting old file {rotatedFile={}}", rotatedFile); boolean deleted = rotatedFile.delete(); if (!deleted) { String message = String.format("failed deleting old file {rotatedFile=%s}", rotatedFile); throw new IOException(message); } } } } }
public RotatingFileOutputStream(RotationConfig config) { this.config = config; this.runningThreads = Collections.synchronizedList(new LinkedList<Thread>()); this.rotationLock = new ReentrantLock(); this.stream = open(); startPolicies(); }
FileOutputStream newStream = open(); FileOutputStream oldStream; Lock writeLock = config.getLock().writeLock(); asyncCompress(policy, dateTime, rotatedFile, config.getCallback()); return;
@Override public void rotate(RotationPolicy policy, LocalDateTime dateTime) { boolean acquired = rotationLock.tryLock(); if (!acquired) { config.getCallback().onConflict(policy, dateTime); } else { try { unsafeRotate(policy, dateTime); } catch (Exception error) { String message = String.format("rotation failure {dateTime=%s}", dateTime); RuntimeException extendedError = new RuntimeException(message); config.getCallback().onFailure(policy, dateTime, null, extendedError); } finally { rotationLock.unlock(); } } }