Logging system redo

This commit is contained in:
Szum123321 2020-06-30 15:54:19 +02:00
parent 92d2d3e2df
commit 35b120ee21
10 changed files with 75 additions and 56 deletions

View File

@ -20,29 +20,25 @@ package net.szum123321.textile_backup;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import io.github.cottonmc.cotton.config.ConfigManager;
import io.github.cottonmc.cotton.logging.ModLogger;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.registry.CommandRegistry;
import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.commands.BlacklistCommand;
import net.szum123321.textile_backup.commands.CleanupCommand;
import net.szum123321.textile_backup.commands.StartBackupCommand;
import net.szum123321.textile_backup.commands.WhitelistCommand;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class TextileBackup implements ModInitializer {
public static final String MOD_ID = "textile_backup";
public static ModLogger logger;
public static final Logger LOGGER = LogManager.getFormatterLogger("Textile Backup");
public static ConfigHandler config;
@Override
public void onInitialize() {
logger = new ModLogger(this.getClass());
logger.info("Loading TextileBackup by Szum123321");
config = ConfigManager.loadConfig(ConfigHandler.class);
registerCommands();
@ -58,7 +54,7 @@ public class TextileBackup implements ModInitializer {
!config.playerBlacklist.contains(ctx.getEntityOrThrow().getEntityName())) ||
(ctx.getMinecraftServer().isSinglePlayer() &&
config.alwaysSingleplayerAllowed);
} catch (Exception e) { //Command was called from server console.
} catch (Exception ignored) { //Command was called from server console.
return true;
}
}

View File

@ -5,7 +5,6 @@ import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import io.github.cottonmc.cotton.config.ConfigManager;
import net.minecraft.command.arguments.EntityArgumentType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
@ -15,7 +14,7 @@ import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.core.Utilities;
public class BlacklistCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register(){
public static LiteralArgumentBuilder<ServerCommandSource> register() {
return CommandManager.literal("blacklist")
.then(CommandManager.literal("add")
.then(CommandManager.argument("player", EntityArgumentType.player())
@ -30,13 +29,13 @@ public class BlacklistCommand {
).executes(ctx -> help(ctx.getSource()));
}
private static int help(ServerCommandSource source){
private static int help(ServerCommandSource source) {
source.sendFeedback(new LiteralText("Available command are: add [player], remove [player], list."), false);
return 1;
}
private static int executeList(ServerCommandSource source){
private static int executeList(ServerCommandSource source) {
StringBuilder builder = new StringBuilder();
builder.append("Currently on the blacklist are: ");
@ -46,7 +45,7 @@ public class BlacklistCommand {
builder.append(", ");
}
Utilities.log(builder.toString(), source);
source.sendFeedback(new LiteralText(builder.toString()), false);
return 1;
}
@ -75,7 +74,7 @@ public class BlacklistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.log(builder.toString(), ctx.getSource());
Utilities.info(builder.toString(), ctx.getSource());
}
return 1;
@ -98,7 +97,7 @@ public class BlacklistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.log(builder.toString(), ctx.getSource());
Utilities.info(builder.toString(), ctx.getSource());
}
return 1;

View File

@ -25,13 +25,12 @@ import net.szum123321.textile_backup.core.BackupHelper;
import net.szum123321.textile_backup.core.Utilities;
public class CleanupCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register(){
public static LiteralArgumentBuilder<ServerCommandSource> register() {
return CommandManager.literal("cleanup")
.executes(ctx -> execute(ctx.getSource()));
}
private static int execute(ServerCommandSource source){
private static int execute(ServerCommandSource source) {
BackupHelper.executeFileLimit(source, Utilities.getLevelName(source.getMinecraftServer()));
return 1;

View File

@ -5,7 +5,6 @@ import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import io.github.cottonmc.cotton.config.ConfigManager;
import net.minecraft.command.arguments.EntityArgumentType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
@ -46,7 +45,7 @@ public class WhitelistCommand {
builder.append(", ");
}
Utilities.log(builder.toString(), source);
source.sendFeedback(new LiteralText(builder.toString()), false);
return 1;
}
@ -75,7 +74,7 @@ public class WhitelistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.log(builder.toString(), ctx.getSource());
Utilities.info(builder.toString(), ctx.getSource());
}
return 1;
@ -97,7 +96,7 @@ public class WhitelistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.log(builder.toString(), ctx.getSource());
Utilities.info(builder.toString(), ctx.getSource());
}
return 1;

View File

@ -49,9 +49,9 @@ public class BackupHelper {
builder.append(" on: ");
builder.append(Utilities.getDateTimeFormatter().format(now));
Utilities.log(builder.toString(), null);
Utilities.info(builder.toString(), null);
Utilities.log("Saving server...", ctx);
Utilities.info("Saving server...", ctx);
if (save)
server.save(true, true, false);
@ -95,11 +95,13 @@ public class BackupHelper {
}
if (now.toEpochSecond(ZoneOffset.UTC) - creationTime.toEpochSecond(ZoneOffset.UTC) > TextileBackup.config.maxAge) {
Utilities.log("Deleting: " + f.getName(), ctx);
Utilities.info("Deleting: " + f.getName(), ctx);
f.delete();
}
} catch (NullPointerException ignored3) {
Utilities.error("File: " + f.getName() + ", was not deleted beacuse could not parse date and time. Please delete it by hand.", ctx);
} catch (NullPointerException e) {
TextileBackup.LOGGER.error("File: {}, was not deleted because could not parse date and time. Please delete it by hand.", f.getName());
Utilities.sendError("File: " + f.getName() + ", was not deleted because could not parse date and time. Please delete it by hand.", ctx);
}
});
}
@ -113,7 +115,7 @@ public class BackupHelper {
Arrays.sort(files);
for (int i = 0; i < var1; i++) {
Utilities.log("Deleting: " + files[i].getName(), ctx);
Utilities.info("Deleting: " + files[i].getName(), ctx);
files[i].delete();
}
}
@ -121,7 +123,7 @@ public class BackupHelper {
if (TextileBackup.config.maxSize > 0 && FileUtils.sizeOfDirectory(root) / 1024 > TextileBackup.config.maxSize) {
Arrays.stream(root.listFiles()).filter(File::isFile).sorted().forEach(e -> {
if (FileUtils.sizeOfDirectory(root) / 1024 > TextileBackup.config.maxSize) {
Utilities.log("Deleting: " + e.getName(), ctx);
Utilities.info("Deleting: " + e.getName(), ctx);
e.delete();
}
});
@ -158,7 +160,7 @@ public class BackupHelper {
try {
path.mkdirs();
} catch (Exception e) {
TextileBackup.logger.error(e.getMessage());
TextileBackup.LOGGER.error("An exception occurred!", e);
return FabricLoader
.getInstance()

View File

@ -24,12 +24,11 @@ import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.dimension.DimensionType;
import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.core.compressors.GenericTarCompressor;
import net.szum123321.textile_backup.core.compressors.LZMACompressor;
import net.szum123321.textile_backup.core.compressors.ParallelBZip2Compressor;
import net.szum123321.textile_backup.core.compressors.ParallelGzipCompressor;
import net.szum123321.textile_backup.core.compressors.ParallelZipCompressor;
import net.szum123321.textile_backup.mixin.MinecraftServerSessionAccessor;
import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream;
import java.io.File;
import java.io.IOException;
@ -48,10 +47,13 @@ public class MakeBackupThread implements Runnable {
@Override
public void run() {
Utilities.info("Starting backup", ctx);
File world = ((MinecraftServerSessionAccessor)server)
.getSession()
.method_27424(RegistryKey.of(Registry.DIMENSION, DimensionType.OVERWORLD_REGISTRY_KEY.getValue()));
TextileBackup.LOGGER.trace("Minecraft world is: {}", world);
File outFile = BackupHelper
.getBackupRootPath(Utilities.getLevelName(server))
@ -59,12 +61,17 @@ public class MakeBackupThread implements Runnable {
.resolve(getFileName())
.toFile();
TextileBackup.LOGGER.trace("Outfile is: {}", outFile);
outFile.getParentFile().mkdirs();
try {
outFile.createNewFile();
} catch (IOException e) {
Utilities.error("Error while trying to create backup file!\n" + e.getMessage(), ctx);
TextileBackup.LOGGER.error("An exception occurred when trying to create new backup file!", e);
Utilities.sendError("An exception occurred when trying to create new backup file!", ctx);
return;
}
@ -76,6 +83,8 @@ public class MakeBackupThread implements Runnable {
coreCount = Math.min(TextileBackup.config.compressionCoreCountLimit, Runtime.getRuntime().availableProcessors());
}
TextileBackup.LOGGER.trace("Running compression on {} threads", coreCount);
switch (TextileBackup.config.format) {
case ZIP:
ParallelZipCompressor.createArchive(world, outFile, ctx, coreCount);
@ -90,18 +99,20 @@ public class MakeBackupThread implements Runnable {
break;
case LZMA:
GenericTarCompressor.createArchive(world, outFile, XZCompressorOutputStream.class, ctx, coreCount);
LZMACompressor.createArchive(world, outFile, ctx); // Always single-threaded ):
break;
default:
Utilities.log("Error! No correct compression format specified! using default compressor!", ctx);
TextileBackup.LOGGER.warn("Specified compressor ({}) is not supported! Zip will be used instead!", TextileBackup.config.format);
Utilities.sendError("Error! No correct compression format specified! using default compressor!", ctx);
ParallelZipCompressor.createArchive(world, outFile, ctx, coreCount);
break;
}
BackupHelper.executeFileLimit(ctx, Utilities.getLevelName(server));
Utilities.log("Done!", ctx);
Utilities.info("Done!", ctx);
}
private String getFileName(){

View File

@ -46,19 +46,17 @@ public class Utilities {
return DateTimeFormatter.ofPattern("dd.MM.yyyy_HH-mm-ss");
}
public static void log(String s, ServerCommandSource ctx){
public static void info(String s, ServerCommandSource ctx){
if(ctx != null)
ctx.sendFeedback(new LiteralText(s), false);
if(TextileBackup.config.log)
TextileBackup.logger.info(s);
TextileBackup.LOGGER.info(s);
}
public static void error(String s, ServerCommandSource ctx){
if(ctx != null)
ctx.sendFeedback(new LiteralText(s).styled(style -> style.withColor(Formatting.RED)), true);
if(TextileBackup.config.log)
TextileBackup.logger.error(s);
public static void sendError(String message, ServerCommandSource source) {
if(source != null) {
source.sendFeedback(new LiteralText(message).styled(style -> style.withColor(Formatting.RED)), false);
}
}
}

View File

@ -14,7 +14,7 @@ import java.nio.file.Files;
public class ParallelBZip2Compressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.log("Starting compression...", ctx);
Utilities.info("Starting compression...", ctx);
BZip2OutputStreamSettings settings = new BZip2OutputStreamSettings().setNumberOfEncoderThreads(coreLimit);
@ -46,17 +46,21 @@ public class ParallelBZip2Compressor {
arc.closeArchiveEntry();
} catch (IOException e) {
TextileBackup.logger.error(e.getMessage());
TextileBackup.LOGGER.error("An exception occurred while trying to compress: " + path.getFileName(), e);
Utilities.sendError("Something went wrong while compressing files!", ctx);
}
});
arc.finish();
} catch (IOException e) {
e.printStackTrace();
TextileBackup.LOGGER.error("An exception occurred!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx);
}
long end = System.nanoTime();
Utilities.log("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
Utilities.info("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
}
}

View File

@ -13,10 +13,12 @@ import java.nio.file.Files;
public class ParallelGzipCompressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.log("Starting compression...", ctx);
Utilities.info("Starting compression...", ctx);
long start = System.nanoTime();
TextileBackup.LOGGER.debug("Compression starts at: {}", start);
try (FileOutputStream outStream = new FileOutputStream(out);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outStream);
ParallelGZIPOutputStream gzipOutputStream = new ParallelGZIPOutputStream(bufferedOutputStream, coreLimit);
@ -43,17 +45,21 @@ public class ParallelGzipCompressor {
arc.closeArchiveEntry();
} catch (IOException e) {
TextileBackup.logger.error(e.getMessage());
TextileBackup.LOGGER.error("An exception occurred while trying to compress file: " + path, e);
Utilities.sendError("Something went wrong while compressing files!", ctx);
}
});
arc.finish();
} catch (IOException e) {
TextileBackup.logger.error(e.toString());
TextileBackup.LOGGER.error("An exception happened!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx);
}
long end = System.nanoTime();
Utilities.log("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
Utilities.info("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
}
}

View File

@ -23,10 +23,12 @@ import java.util.zip.ZipEntry;
public class ParallelZipCompressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.log("Starting compression...", ctx);
Utilities.info("Starting compression...", ctx);
long start = System.nanoTime();
TextileBackup.LOGGER.debug("Compression starts at: {}", start);
try (FileOutputStream fileOutputStream = new FileOutputStream(out);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
ZipArchiveOutputStream arc = new ZipArchiveOutputStream(bufferedOutputStream)) {
@ -55,12 +57,14 @@ public class ParallelZipCompressor {
arc.finish();
} catch (IOException | InterruptedException | ExecutionException e) {
TextileBackup.logger.error(e.getMessage());
TextileBackup.LOGGER.error("An exception happened!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx);;
}
long end = System.nanoTime();
Utilities.log("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
Utilities.info("Compression took: " + ((end - start) / 1000000000.0) + "s", ctx);
}
static class FileInputStreamSupplier implements InputStreamSupplier {
@ -75,8 +79,9 @@ public class ParallelZipCompressor {
try {
stream = Files.newInputStream(sourceFile);
} catch (IOException e) {
e.printStackTrace();
TextileBackup.LOGGER.error("An exception occurred while trying to create input stream!", e);
}
return stream;
}
}