73 lines
2.6 KiB
Java
73 lines
2.6 KiB
Java
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 BASE_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-ss");
|
|
|
|
public LogWriter() {
|
|
createFolder(BASE_FOLDER);
|
|
createFolder(ZIP_FOLDER);
|
|
}
|
|
|
|
public void logToCategory(String category, String message) {
|
|
String folderPath = BASE_FOLDER + category + "/";
|
|
createFolder(folderPath);
|
|
|
|
String fileName = "log_" + FORMAT.format(new Date()) + ".log";
|
|
File file = new File(folderPath, fileName);
|
|
|
|
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
|
|
String entry = "[" + FORMAT.format(new Date()) + "] " + message;
|
|
writer.write(entry);
|
|
writer.newLine();
|
|
} catch (IOException e) {
|
|
System.err.println("Failed to write log to " + category + ": " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
private void createFolder(String path) {
|
|
File folder = new File(path);
|
|
if (!folder.exists()) folder.mkdirs();
|
|
}
|
|
|
|
public void zipLogs() {
|
|
String zipName = "logs_" + FORMAT.format(new Date()) + ".zip";
|
|
File zipFile = new File(ZIP_FOLDER + zipName);
|
|
|
|
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
|
|
Path basePath = Paths.get(BASE_FOLDER);
|
|
|
|
Files.walk(basePath)
|
|
.filter(Files::isRegularFile)
|
|
.forEach(path -> {
|
|
try (InputStream is = Files.newInputStream(path)) {
|
|
String entryName = basePath.relativize(path).toString().replace("\\", "/");
|
|
zos.putNextEntry(new ZipEntry(entryName));
|
|
|
|
byte[] buffer = new byte[4096];
|
|
int len;
|
|
while ((len = is.read(buffer)) > 0) {
|
|
zos.write(buffer, 0, len);
|
|
}
|
|
zos.closeEntry();
|
|
} catch (IOException e) {
|
|
System.err.println("Failed to zip file: " + path + " — " + e.getMessage());
|
|
}
|
|
});
|
|
|
|
System.out.println("[ServerDevMode] Logs zipped to " + zipFile.getName());
|
|
} catch (IOException e) {
|
|
System.err.println("Failed to create zip file: " + e.getMessage());
|
|
}
|
|
}
|
|
}
|