Skip to content

Commit

Permalink
improve logger management
Browse files Browse the repository at this point in the history
use stream calls where possible
overall improvements
  • Loading branch information
xGinko committed Mar 5, 2024
1 parent 3edcf94 commit 3a7a0a4
Show file tree
Hide file tree
Showing 122 changed files with 706 additions and 788 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import me.moomoo.anarchyexploitfixes.config.LanguageCache;
import me.moomoo.anarchyexploitfixes.modules.AnarchyExploitFixesModule;
import me.moomoo.anarchyexploitfixes.utils.models.TPSCache;
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
import org.bstats.bukkit.Metrics;
import org.bukkit.NamespacedKey;
import org.bukkit.command.CommandSender;
Expand All @@ -20,7 +21,6 @@
import java.util.Locale;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
Expand All @@ -32,65 +32,66 @@ public class AnarchyExploitFixes extends JavaPlugin {
private static HashMap<String, LanguageCache> languageCacheMap;
private static Config config;
private static TPSCache tpsCache;
private static Logger logger;
private static ComponentLogger prefixedLogger, unPrefixedLogger;
private static Metrics metrics;
private static boolean isServerFolia, foundProtocolLib;

@Override
public void onEnable() {
instance = this;
logger = getLogger();
prefixedLogger = ComponentLogger.logger(getLogger().getName());
unPrefixedLogger = ComponentLogger.logger("");

// Fancy enable
logger.info(" ");
logger.info(" ");
logger.info(" █████ ███████ ███████ ");
logger.info(" ██ ██ ██ ██ AnarchyExploitFixes ");
logger.info(" ███████ █████ █████ Made by moom0o ");
logger.info(" ██ ██ ██ ██ Rewritten by xGinko ");
logger.info(" ██ ██ ███████ ██ ");
logger.info(" ");
logger.info(" ");
prefixedLogger.info(" ");
prefixedLogger.info(" ");
prefixedLogger.info(" █████ ███████ ███████ ");
prefixedLogger.info(" ██ ██ ██ ██ AnarchyExploitFixes ");
prefixedLogger.info(" ███████ █████ █████ Made by moom0o ");
prefixedLogger.info(" ██ ██ ██ ██ Rewritten by xGinko ");
prefixedLogger.info(" ██ ██ ███████ ██ ");
prefixedLogger.info(" ");
prefixedLogger.info(" ");

// Check for paper as the api is needed for this plugin
if (!PaperLib.isPaper()) {
logger.severe("##########################################################");
logger.severe("# #");
logger.severe("# ERROR #");
logger.severe("# #");
logger.severe("# This plugin requires at least a paper or paper #");
logger.severe("# fork server. #");
logger.severe("# #");
logger.severe("##########################################################");
prefixedLogger.error("##########################################################");
prefixedLogger.error("# #");
prefixedLogger.error("# ERROR #");
prefixedLogger.error("# #");
prefixedLogger.error("# This plugin requires at least a paper or paper #");
prefixedLogger.error("# fork server. #");
prefixedLogger.error("# #");
prefixedLogger.error("##########################################################");
getServer().getPluginManager().disablePlugin(this);
return;
}

logger.info("Detected Version 1." + PaperLib.getMinecraftVersion() + "." + PaperLib.getMinecraftPatchVersion());
prefixedLogger.info("Detected Version 1." + PaperLib.getMinecraftVersion() + "." + PaperLib.getMinecraftPatchVersion());
foundProtocolLib = getServer().getPluginManager().isPluginEnabled("ProtocolLib");
logger.info(foundProtocolLib ? "Found ProtocolLib" : "Could not find ProtocolLib");
prefixedLogger.info(foundProtocolLib ? "Found ProtocolLib" : "Could not find ProtocolLib");

try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
logger.info("Detected Folia server");
prefixedLogger.info("Detected Folia server");
isServerFolia = true;
} catch (ClassNotFoundException e) {
isServerFolia = false;
}

logger.info("Loading Translations");
prefixedLogger.info("Loading Translations");
reloadLang();

logger.info("Loading Config");
prefixedLogger.info("Loading Config");
reloadConfiguration();

logger.info("Registering Commands");
prefixedLogger.info("Registering Commands");
AnarchyExploitFixesCommand.registerCommands();

logger.info("Loading metrics");
prefixedLogger.info("Loading metrics");
metrics = new Metrics(this, 8700);

logger.info("Done.");
prefixedLogger.info("Done.");
}

@Override
Expand All @@ -106,7 +107,7 @@ public void onDisable() {
config = null;
languageCacheMap = null;
tpsCache = null;
logger = null;
prefixedLogger = null;
isServerFolia = foundProtocolLib = false;
}

Expand All @@ -125,8 +126,11 @@ public static Config getConfiguration() {
public static NamespacedKey getKey(String key) {
return new NamespacedKey(instance, key);
}
public static Logger getLog() {
return logger;
public static ComponentLogger getPrefixedLogger() {
return prefixedLogger;
}
public static ComponentLogger getUnprefixedLogger() {
return unPrefixedLogger;
}
public static LanguageCache getLang(Locale locale) {
return getLang(locale.toString().toLowerCase());
Expand Down Expand Up @@ -157,8 +161,7 @@ private void reloadConfiguration() {
AnarchyExploitFixesModule.reloadModules();
config.saveConfig();
} catch (Exception e) {
logger.severe("Failed to load config file! - " + e.getLocalizedMessage());
e.printStackTrace();
prefixedLogger.error("Failed loading config!", e);
}
}

Expand All @@ -169,7 +172,7 @@ private void reloadLang() {
Files.createDirectories(langDirectory.toPath());
for (String fileName : getDefaultLanguageFiles()) {
final String localeString = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.lastIndexOf('.'));
logger.info("Found language file for " + localeString);
prefixedLogger.info("Found language file for " + localeString);
languageCacheMap.put(localeString, new LanguageCache(localeString));
}
final Pattern langPattern = Pattern.compile("([a-z]{1,3}_[a-z]{1,3})(\\.yml)", Pattern.CASE_INSENSITIVE);
Expand All @@ -178,14 +181,13 @@ private void reloadLang() {
if (langMatcher.find()) {
final String localeString = langMatcher.group(1).toLowerCase();
if (!languageCacheMap.containsKey(localeString)) { // make sure it wasn't a default file that we already loaded
logger.info("Found language file for " + localeString);
prefixedLogger.info("Found language file for " + localeString);
languageCacheMap.put(localeString, new LanguageCache(localeString));
}
}
}
} catch (Exception e) {
e.printStackTrace();
logger.severe("Error loading language files! Language files will not reload to avoid errors, make sure to correct this before restarting the server!");
} catch (Throwable t) {
prefixedLogger.error("Error loading language files!", t);
}
}

Expand All @@ -196,7 +198,7 @@ private Set<String> getDefaultLanguageFiles() {
.filter(name -> name.startsWith("lang/") && name.endsWith(".yml"))
.collect(Collectors.toSet());
} catch (IOException e) {
logger.severe("Failed getting default lang files! - "+e.getLocalizedMessage());
prefixedLogger.error("Failed getting default lang files!", e);
return Collections.emptySet();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Sound;
import org.slf4j.event.Level;

import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;

public class Config {

Expand All @@ -32,7 +32,7 @@ public Config() throws Exception {
// Create plugin folder first if it does not exist yet
File pluginFolder = AnarchyExploitFixes.getInstance().getDataFolder();
if (!pluginFolder.exists() && !pluginFolder.mkdir())
AnarchyExploitFixes.getLog().severe("Failed to create plugin folder.");
AnarchyExploitFixes.getPrefixedLogger().error("Failed to create plugin folder.");
// Load config.yml with ConfigMaster
this.config = ConfigFile.loadConfig(new File(pluginFolder, "config.yml"));
// Pre-structure to force order
Expand Down Expand Up @@ -75,7 +75,7 @@ public Config() throws Exception {
try {
parsedSound = Sound.valueOf(configuredSound);
} catch (IllegalArgumentException e) {
LogUtil.moduleLog(Level.WARNING, "elytra-speed", "Sound '"+configuredSound+"' does not exist on this version. Using default.");
LogUtil.moduleLog(Level.WARN, "elytra-speed", "Sound '"+configuredSound+"' does not exist on this version. Using default.");
parsedSound = Sound.ENTITY_EXPERIENCE_ORB_PICKUP;
}
this.elytra_too_fast_sound = parsedSound;
Expand All @@ -98,7 +98,7 @@ public void saveConfig() {
try {
config.save();
} catch (Exception e) {
AnarchyExploitFixes.getLog().severe("Failed to save config file! - " + e.getLocalizedMessage());
AnarchyExploitFixes.getPrefixedLogger().error("Failed to save config file!", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public LanguageCache(String locale) throws Exception {
// Check if the lang folder has already been created
File parent = langYML.getParentFile();
if (!parent.exists() && !parent.mkdir())
AnarchyExploitFixes.getLog().severe("Unable to create lang directory.");
AnarchyExploitFixes.getPrefixedLogger().error("Unable to create lang directory.");
// Check if the file already exists and save the one from the plugin's resources folder if it does not
if (!langYML.exists())
plugin.saveResource("lang/" + locale + ".yml", false);
Expand Down Expand Up @@ -129,7 +129,7 @@ public LanguageCache(String locale) throws Exception {
try {
lang.save();
} catch (Exception e) {
AnarchyExploitFixes.getLog().severe("Failed to save language file: "+ langYML.getName() +" - " + e.getLocalizedMessage());
AnarchyExploitFixes.getPrefixedLogger().error("Failed to save language file: "+ langYML.getName() +"!", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ static void reloadModules() {
modules.add(new AntiTagParserCrash());

if (!AnarchyExploitFixes.getConfiguration().protocolLib_IsDisabled && !protocolLibIsInstalled) {
AnarchyExploitFixes.getLog().severe("Could not find ProtocolLib. Packet exploits cannot be patched without it.");
AnarchyExploitFixes.getLog().severe("Download at: https://www.spigotmc.org/resources/protocollib.1997/");
AnarchyExploitFixes.getPrefixedLogger().error("Could not find ProtocolLib. Packet exploits cannot be patched without it.");
AnarchyExploitFixes.getPrefixedLogger().error("Download at: https://www.spigotmc.org/resources/protocollib.1997/");
}

for (AnarchyExploitFixesModule module : modules) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.slf4j.event.Level;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;

public class PreventGoingBelowBedrockFloor implements AnarchyExploitFixesModule, Listener {

Expand All @@ -29,7 +29,7 @@ public PreventGoingBelowBedrockFloor() {
shouldEnable();
Config config = AnarchyExploitFixes.getConfiguration();
config.addComment("bedrock.prevent-going-below-bedrock-floor.enable",
"Prevents players from going below bedrock the bedrock floor.");
"Prevents players from going below the bedrock floor.");
this.teleport_enabled = config.getBoolean("bedrock.prevent-going-below-bedrock-floor.teleport", true,
"Teleports the player above the bedrock");
this.eject_enabled = config.getBoolean("bedrock.prevent-going-below-bedrock-floor.eject-player", true,
Expand All @@ -44,7 +44,7 @@ public PreventGoingBelowBedrockFloor() {
try {
filler_material = Material.valueOf(configuredFillMaterial);
} catch (IllegalArgumentException e) {
LogUtil.materialNotRecognized(Level.WARNING, name(), configuredFillMaterial);
LogUtil.materialNotRecognized(Level.WARN, name(), configuredFillMaterial);
}
this.fillMaterial = filler_material;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void onPacketReceiving(PacketEvent event) {
event.setCancelled(true);
player.sendMessage(AnarchyExploitFixes.getLang(player.locale()).chat_commandwhitelist_badcommand);
if (shouldLog)
AnarchyExploitFixes.getLog().info(player.getName() + " tried to execute a non whitelisted command: " + message);
AnarchyExploitFixes.getPrefixedLogger().info(player.getName() + " tried to execute a non whitelisted command: " + message);
return;
}

Expand All @@ -53,7 +53,7 @@ public void onPacketReceiving(PacketEvent event) {
event.setCancelled(true);
player.sendMessage(AnarchyExploitFixes.getLang(player.locale()).chat_commandwhitelist_badcommand);
if (shouldLog)
AnarchyExploitFixes.getLog().info(player.getName() + " tried to execute a blacklisted subcommand: " + message);
AnarchyExploitFixes.getPrefixedLogger().info(player.getName() + " tried to execute a blacklisted subcommand: " + message);
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.event.server.TabCompleteEvent;
import org.slf4j.event.Level;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.stream.Collectors;

public class CommandWhitelist implements AnarchyExploitFixesModule, Listener {
Expand Down Expand Up @@ -71,12 +71,12 @@ public void enable() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
if (shouldUseProtocolLib) {
if (AnarchyExploitFixes.getConfiguration().protocolLib_IsDisabled) {
LogUtil.moduleLog(Level.WARNING, name(), "Can't enable packet listener(s) because ProtocolLib is disabled in config.");
LogUtil.moduleLog(Level.WARN, name(), "Can't enable packet listener(s) because ProtocolLib is disabled in config.");
} else {
if (AnarchyExploitFixes.isProtocolLibInstalled()) {
new CWChatPacketListener(plugin, allowedCommands, bannedSubCommands, shouldLog).register();
} else {
LogUtil.moduleLog(Level.SEVERE, name(), "Can't enable packet listener(s) because ProtocolLib is missing.");
LogUtil.moduleLog(Level.ERROR, name(), "Can't enable packet listener(s) because ProtocolLib is missing.");
}
}
}
Expand Down Expand Up @@ -107,7 +107,7 @@ private void onCommandPreProcess(PlayerCommandPreprocessEvent event) {
event.setCancelled(true);
player.sendMessage(AnarchyExploitFixes.getLang(player.locale()).chat_commandwhitelist_badcommand);
if (shouldLog)
AnarchyExploitFixes.getLog().info(player.getName() + " tried to execute a non whitelisted command: " + fullCommand);
AnarchyExploitFixes.getPrefixedLogger().info(player.getName() + " tried to execute a non whitelisted command: " + fullCommand);
return;
}

Expand All @@ -116,7 +116,7 @@ private void onCommandPreProcess(PlayerCommandPreprocessEvent event) {
event.setCancelled(true);
player.sendMessage(AnarchyExploitFixes.getLang(player.locale()).chat_commandwhitelist_badcommand);
if (shouldLog)
AnarchyExploitFixes.getLog().info(player.getName() + " tried to execute a blacklisted subcommand: " + message);
AnarchyExploitFixes.getPrefixedLogger().info(player.getName() + " tried to execute a blacklisted subcommand: " + message);
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.slf4j.event.Level;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

public class BlockLimit implements AnarchyExploitFixesModule, Listener {

Expand Down Expand Up @@ -129,9 +129,9 @@ public BlockLimit() {
Integer maxAmountPerChunk = Integer.valueOf(section.getString(configuredMaterial));
this.blockLimits.put(blockMaterial, maxAmountPerChunk);
} catch (NumberFormatException e) {
LogUtil.integerNotRecognized(Level.WARNING, name(), configuredMaterial);
LogUtil.integerNotRecognized(Level.WARN, name(), configuredMaterial);
} catch (IllegalArgumentException e) {
LogUtil.materialNotRecognized(Level.WARNING, name(), configuredMaterial);
LogUtil.materialNotRecognized(Level.WARN, name(), configuredMaterial);
}
}
}
Expand Down
Loading

0 comments on commit 3a7a0a4

Please sign in to comment.