Update LogWriter.java
This commit is contained in:
@@ -1 +1,76 @@
|
||||
package com.minster586.devmode;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class LogWriter {
|
||||
|
||||
private static final String LOG_FOLDER = "plugins/ServerDevMode/logs/";
|
||||
private static final String ZIP_FOLDER = "plugins/ServerDevMode/zipped_logs/";
|
||||
private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
|
||||
|
||||
private BufferedWriter currentWriter;
|
||||
|
||||
public LogWriter() {
|
||||
prepareDirectories();
|
||||
rotateLogFile(); // Start fresh
|
||||
}
|
||||
|
||||
private void prepareDirectories() {
|
||||
new File(LOG_FOLDER).mkdirs();
|
||||
new File(ZIP_FOLDER).mkdirs();
|
||||
}
|
||||
|
||||
public void rotateLogFile() {
|
||||
try {
|
||||
if (currentWriter != null) currentWriter.close();
|
||||
String timestamp = FORMAT.format(new Date());
|
||||
File file = new File(LOG_FOLDER + "devlog_" + timestamp + ".log");
|
||||
currentWriter = new BufferedWriter(new FileWriter(file));
|
||||
log("Log file initialized at " + timestamp);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void log(String message) {
|
||||
try {
|
||||
String entry = "[" + FORMAT.format(new Date()) + "] " + message;
|
||||
currentWriter.write(entry);
|
||||
currentWriter.newLine();
|
||||
currentWriter.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void zipLogs() {
|
||||
String zipName = "logs_" + FORMAT.format(new Date()) + ".zip";
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZIP_FOLDER + zipName))) {
|
||||
Files.walk(Paths.get(LOG_FOLDER))
|
||||
.filter(Files::isRegularFile)
|
||||
.forEach(path -> {
|
||||
try (InputStream is = Files.newInputStream(path)) {
|
||||
ZipEntry entry = new ZipEntry(path.getFileName().toString());
|
||||
zos.putNextEntry(entry);
|
||||
byte[] buffer = new byte[4096];
|
||||
int len;
|
||||
while ((len = is.read(buffer)) > 0) {
|
||||
zos.write(buffer, 0, len);
|
||||
}
|
||||
zos.closeEntry();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
|
||||
System.out.println("[DevMode] Zipped logs to " + zipName);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user