From b7e986506d03acfa10475329306c3a1634275266 Mon Sep 17 00:00:00 2001 From: Laurent Clouet <4409640-laurent.clouet@users.noreply.gitlab.com> Date: Fri, 25 Oct 2024 10:06:33 +0000 Subject: [PATCH] Feat: limit size of log file --- src/main/java/com/sheepit/client/Client.java | 2 ++ src/main/java/com/sheepit/client/Log.java | 33 ++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/main/java/com/sheepit/client/Client.java b/src/main/java/com/sheepit/client/Client.java index c6d07a5..58bdfaf 100644 --- a/src/main/java/com/sheepit/client/Client.java +++ b/src/main/java/com/sheepit/client/Client.java @@ -211,6 +211,8 @@ import okhttp3.HttpUrl; } } + this.log.shrink(); + step = this.log.newCheckPoint(); try { Calendar nextRequest = this.nextJobRequest(); diff --git a/src/main/java/com/sheepit/client/Log.java b/src/main/java/com/sheepit/client/Log.java index 47a97ac..bdc9ded 100644 --- a/src/main/java/com/sheepit/client/Log.java +++ b/src/main/java/com/sheepit/client/Log.java @@ -21,7 +21,9 @@ package com.sheepit.client; import java.io.File; import java.io.IOException; +import java.io.RandomAccessFile; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.DateFormat; @@ -38,6 +40,9 @@ public final class Log { private final String LEVEL_INFO = "info"; private final String LEVEL_ERROR = "error"; + public final int MAX_SIZE = 10000000; // in B + public final int PERIOD = 3600000; // duration in ms between two shrink + private static Log instance = null; private Map> checkpoints = new HashMap<>(); @@ -49,6 +54,8 @@ public final class Log { private String logFile; + private long lastShrink; + private Log(boolean debugLevel_, boolean print_, String logDirectory_) { this.debugLevel = debugLevel_; this.printStdOut = print_; @@ -56,6 +63,7 @@ public final class Log { this.lastCheckPoint = 0; this.checkpoints.put(this.lastCheckPoint, new ArrayList()); this.dateFormat = new SimpleDateFormat("dd-MM HH:mm:ss"); + this.lastShrink = 0; } public void debug(String msg_) { @@ -137,6 +145,31 @@ public final class Log { } } + public synchronized void shrink() { + if (System.currentTimeMillis() > (this.lastShrink + this.PERIOD)) { + try (RandomAccessFile raf = new RandomAccessFile(this.logFile, "r")) { + long fileLength = raf.length(); + if (fileLength < MAX_SIZE) { // nothing to do, it's a small file + return; + } + long startPosition = Math.max(0, fileLength - MAX_SIZE); + + raf.seek(startPosition); + + byte[] newBytes = new byte[(int) (fileLength - startPosition)]; + raf.readFully(newBytes); + + Path inputPath = Paths.get(this.logFile); + Files.write(inputPath, newBytes); + } + catch (IOException e) { + e.printStackTrace(); + } + + this.lastShrink = System.currentTimeMillis(); + } + } + public static synchronized Log getInstance(Configuration config) { if (instance == null) { String path = null;