AutomaticLogDeleter/src/main/java/net/limework/automaticlogdeleter/AutomaticLogDeleter.java

66 lines
2.0 KiB
Java
Raw Normal View History

2021-06-12 11:43:58 +00:00
package net.limework.automaticlogdeleter;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.logging.Level;
2021-06-12 11:56:02 +00:00
public class AutomaticLogDeleter extends JavaPlugin {
2021-06-12 11:43:58 +00:00
@Override
public void onEnable() {
new Thread(() -> {
this.saveDefaultConfig();
deleteLogs();
}).start();
}
@Override
public void onDisable() {
2021-06-12 11:47:13 +00:00
FileConfiguration config = getConfig();
if (config.getBoolean("also-delete-logs-on-shutdown")) {
//we aren't using separate thread here, so it has time to finish before server shutdowns
2021-06-12 12:11:03 +00:00
deleteLogs();
2021-06-12 11:47:13 +00:00
}
2021-06-12 11:43:58 +00:00
}
public void deleteLogs() {
File path = new File("logs");
File[] files = path.listFiles();
if (files == null) { return; }
FileConfiguration config = getConfig();
//maximum file age allowed
long maxOldMillis = config.getLong("delete-logs-older-than-seconds") * 1000;
2021-06-13 09:12:06 +00:00
String fileName;
2021-06-12 11:43:58 +00:00
for (File file : files) {
if (file.isFile()) {
2021-06-13 09:12:06 +00:00
fileName = file.getName();
//if file is not a log file
2021-06-13 09:30:35 +00:00
//using contains to make it more likely to catch different types of logging systems
if (!fileName.contains(".log") && !fileName.contains("log.")) {
2021-06-13 09:12:06 +00:00
continue;
}
//if file is older than configured time
2021-06-15 07:04:57 +00:00
if ((System.currentTimeMillis() - file.lastModified()) < maxOldMillis) {
2021-06-13 09:12:06 +00:00
continue;
}
2021-06-12 11:43:58 +00:00
2021-06-13 09:12:06 +00:00
if (!file.delete()) {
2021-06-15 07:04:57 +00:00
getLogger().log(Level.WARNING, "[AutomaticLogDeleter] Failed to delete server log file! Are you sure the file permissions are correct?");
2021-06-13 09:12:06 +00:00
} else {
2021-06-15 07:04:57 +00:00
getLogger().log(Level.INFO, "[AutomaticLogDeleter] Deleted log file " + fileName);
2021-06-12 11:43:58 +00:00
}
}
}
}
}