diff --git a/Essentials/src/main/java/com/earth2me/essentials/AlternativeCommandsHandler.java b/Essentials/src/main/java/com/earth2me/essentials/AlternativeCommandsHandler.java index b5d86018269..322cebb4d9f 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/AlternativeCommandsHandler.java +++ b/Essentials/src/main/java/com/earth2me/essentials/AlternativeCommandsHandler.java @@ -11,10 +11,8 @@ import java.util.Locale; import java.util.Map; import java.util.logging.Level; -import java.util.logging.Logger; public class AlternativeCommandsHandler { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient Map> altcommands = new HashMap<>(); private final transient Map disabledList = new HashMap<>(); private final transient IEssentials ess; @@ -95,7 +93,7 @@ public void executed(final String label, final Command pc) { if (pc instanceof PluginIdentifiableCommand) { final String altString = ((PluginIdentifiableCommand) pc).getPlugin().getName() + ":" + pc.getName(); if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + altString); + ess.getLogger().log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + altString); } disabledList.put(label, altString); } diff --git a/Essentials/src/main/java/com/earth2me/essentials/Backup.java b/Essentials/src/main/java/com/earth2me/essentials/Backup.java index 101e7d25ec3..c4ddc2f490f 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Backup.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Backup.java @@ -10,12 +10,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class Backup implements Runnable { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private transient final Server server; private transient final IEssentials ess; private final AtomicBoolean pendingShutdown = new AtomicBoolean(false); @@ -81,7 +79,7 @@ public void run() { taskLock.complete(new Object()); return; } - LOGGER.log(Level.INFO, tl("backupStarted")); + ess.getLogger().log(Level.INFO, tl("backupStarted")); final CommandSender cs = server.getConsoleSender(); server.dispatchCommand(cs, "save-all"); server.dispatchCommand(cs, "save-off"); @@ -99,17 +97,17 @@ public void run() { do { line = reader.readLine(); if (line != null) { - LOGGER.log(Level.INFO, line); + ess.getLogger().log(Level.INFO, line); } } while (line != null); } } catch (final IOException ex) { - LOGGER.log(Level.SEVERE, null, ex); + ess.getLogger().log(Level.SEVERE, null, ex); } }); child.waitFor(); } catch (final InterruptedException | IOException ex) { - LOGGER.log(Level.SEVERE, null, ex); + ess.getLogger().log(Level.SEVERE, null, ex); } finally { class BackupEnableSaveTask implements Runnable { @Override @@ -120,7 +118,7 @@ public void run() { } active = false; taskLock.complete(new Object()); - LOGGER.log(Level.INFO, tl("backupFinished")); + ess.getLogger().log(Level.INFO, tl("backupFinished")); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/Essentials.java b/Essentials/src/main/java/com/earth2me/essentials/Essentials.java index 9ab438975d4..8ed17dc6184 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Essentials.java @@ -72,6 +72,7 @@ import net.ess3.provider.SpawnerItemProvider; import net.ess3.provider.SyncCommandsProvider; import net.ess3.provider.WorldInfoProvider; +import net.ess3.provider.providers.BaseLoggerProvider; import net.ess3.provider.providers.BasePotionDataProvider; import net.ess3.provider.providers.BlockMetaSpawnerItemProvider; import net.ess3.provider.providers.BukkitMaterialTagProvider; @@ -93,7 +94,6 @@ import net.ess3.provider.providers.PaperServerStateProvider; import net.essentialsx.api.v2.services.BalanceTop; import net.essentialsx.api.v2.services.mail.MailService; -import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; @@ -141,7 +141,8 @@ import static com.earth2me.essentials.I18n.tl; public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { - private static final Logger LOGGER = Logger.getLogger("Essentials"); + private static final Logger BUKKIT_LOGGER = Logger.getLogger("Essentials"); + private static Logger LOGGER = null; private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this); private final transient Set vanishedPlayers = new LinkedHashSet<>(); private transient ISettings settings; @@ -204,6 +205,7 @@ public ISettings getSettings() { } public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException { + LOGGER = new BaseLoggerProvider(BUKKIT_LOGGER); final File dataFolder = File.createTempFile("essentialstest", ""); if (!dataFolder.delete()) { throw new IOException(); @@ -244,9 +246,11 @@ public void onLoad() { @Override public void onEnable() { try { - if (LOGGER != this.getLogger()) { - LOGGER.setParent(this.getLogger()); + if (BUKKIT_LOGGER != super.getLogger()) { + BUKKIT_LOGGER.setParent(super.getLogger()); } + LOGGER = EssentialsLogger.getLoggerProvider(this); + execTimer = new ExecuteTimer(); execTimer.start(); i18n = new I18n(this); @@ -484,6 +488,24 @@ public void onEnable() { getBackup().setPendingShutdown(false); } + @Override + public Logger getLogger() { + if (LOGGER != null) { + return LOGGER; + } + + return super.getLogger(); + } + + // Returns our provider logger if available + public static Logger getWrappedLogger() { + if (LOGGER != null) { + return LOGGER; + } + + return BUKKIT_LOGGER; + } + @Override public void saveConfig() { // We don't use any of the bukkit config writing, as this breaks our config file formatting. @@ -632,7 +654,7 @@ public List onTabCompleteEssentials(final CommandSender cSender, final C return completer.onTabComplete(cSender, command, commandLabel, args); } } catch (final Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } } } @@ -713,7 +735,7 @@ public boolean onCommandEssentials(final CommandSender cSender, final Command co try { pc.execute(cSender, commandLabel, args); } catch (final Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); cSender.sendMessage(tl("internalError")); } return true; @@ -733,10 +755,10 @@ public boolean onCommandEssentials(final CommandSender cSender, final Command co if (bSenderBlock != null) { if (getSettings().logCommandBlockCommands()) { - Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[] {bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + LOGGER.log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[] {bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); } } else if (user == null) { - Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[] {cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + LOGGER.log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[] {cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); } final CommandSource sender = new CommandSource(cSender); diff --git a/Essentials/src/main/java/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/main/java/com/earth2me/essentials/EssentialsEntityListener.java index c8040c660c6..ba305ec0b93 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/EssentialsEntityListener.java +++ b/Essentials/src/main/java/com/earth2me/essentials/EssentialsEntityListener.java @@ -30,13 +30,11 @@ import java.util.List; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; public class EssentialsEntityListener implements Listener { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}"); private final IEssentials ess; @@ -110,7 +108,7 @@ class PowerToolInteractTask implements Runnable { @Override public void run() { attacker.getBase().chat("/" + command); - LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command)); + ess.getLogger().log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command)); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/EssentialsLogger.java b/Essentials/src/main/java/com/earth2me/essentials/EssentialsLogger.java new file mode 100644 index 00000000000..5190bb66e67 --- /dev/null +++ b/Essentials/src/main/java/com/earth2me/essentials/EssentialsLogger.java @@ -0,0 +1,46 @@ +package com.earth2me.essentials; + +import net.ess3.nms.refl.ReflUtil; +import net.ess3.provider.LoggerProvider; +import net.ess3.provider.providers.BaseLoggerProvider; +import net.ess3.provider.providers.PaperLoggerProvider; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +public final class EssentialsLogger { + private final static Map loggerProviders = new HashMap<>(); + + private EssentialsLogger() { + } + + public static LoggerProvider getLoggerProvider(final Plugin plugin) { + if (loggerProviders.containsKey(plugin.getName())) { + return loggerProviders.get(plugin.getName()); + } + + final LoggerProvider provider; + if (ReflUtil.getClassCached("io.papermc.paper.adventure.providers.ComponentLoggerProviderImpl") != null) { + provider = new PaperLoggerProvider(plugin); + } else { + provider = new BaseLoggerProvider(Logger.getLogger(plugin.getName())); + } + loggerProviders.put(plugin.getName(), provider); + return provider; + } + + public static LoggerProvider getLoggerProvider(final String pluginName) { + if (loggerProviders.containsKey(pluginName)) { + return loggerProviders.get(pluginName); + } + + final Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName); + if (plugin == null) { + throw new IllegalArgumentException("Plugin not found: " + pluginName); + } + return getLoggerProvider(plugin); + } +} diff --git a/Essentials/src/main/java/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/main/java/com/earth2me/essentials/EssentialsPlayerListener.java index 22acba962be..8e444c6c76d 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/EssentialsPlayerListener.java +++ b/Essentials/src/main/java/com/earth2me/essentials/EssentialsPlayerListener.java @@ -72,13 +72,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; public class EssentialsPlayerListener implements Listener, FakeAccessor { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient IEssentials ess; private final ConcurrentHashMap pendingMotdTasks = new ConcurrentHashMap<>(); @@ -166,7 +164,7 @@ public void onPlayerChat(final AsyncPlayerChatEvent event) { user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); } - LOGGER.info(tl("mutedUserSpeaks", user.getName(), event.getMessage())); + ess.getLogger().info(tl("mutedUserSpeaks", user.getName(), event.getMessage())); } try { final Iterator it = event.getRecipients().iterator(); @@ -198,7 +196,7 @@ public void onPlayerMove(final PlayerMoveEvent event) { event.getHandlers().unregister(this); if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, "Unregistering move listener"); + ess.getLogger().log(Level.INFO, "Unregistering move listener"); } return; @@ -464,9 +462,9 @@ public void run() { tempInput = new TextInput(user.getSource(), "motd", true, ess); } catch (final IOException ex) { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); + ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); } else { - LOGGER.log(Level.WARNING, ex.getMessage()); + ess.getLogger().log(Level.WARNING, ex.getMessage()); } } } @@ -626,7 +624,7 @@ public void handlePlayerCommandPreprocess(final PlayerCommandPreprocessEvent eve } else { player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); } - LOGGER.info(tl("mutedUserSpeaks", player.getName(), event.getMessage())); + ess.getLogger().info(tl("mutedUserSpeaks", player.getName(), event.getMessage())); return; } @@ -814,7 +812,7 @@ public void run() { ess.scheduleSyncDelayedTask(new DelayedClickJumpTask()); } catch (final Exception ex) { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); + ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); } } } @@ -838,7 +836,7 @@ class PowerToolUseTask implements Runnable { @Override public void run() { user.getBase().chat("/" + command); - LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command)); + ess.getLogger().log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command)); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials/src/main/java/com/earth2me/essentials/EssentialsUpgrade.java index 5511967cf5d..3c4cce66b46 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/EssentialsUpgrade.java +++ b/Essentials/src/main/java/com/earth2me/essentials/EssentialsUpgrade.java @@ -47,14 +47,12 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; public class EssentialsUpgrade { - private final static Logger LOGGER = Logger.getLogger("Essentials"); private static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml"); private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$"; private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX); @@ -186,13 +184,13 @@ public void convertMailList() { config.blockingSave(); } } catch (RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); throw ex; } } doneFile.setProperty("updateUsersMailList", true); doneFile.save(); - LOGGER.info("Done converting mail list."); + ess.getLogger().info("Done converting mail list."); } public void convertStupidCamelCaseUserdataKeys() { @@ -200,7 +198,7 @@ public void convertStupidCamelCaseUserdataKeys() { return; } - LOGGER.info("Attempting to migrate legacy userdata keys to Configurate"); + ess.getLogger().info("Attempting to migrate legacy userdata keys to Configurate"); final File userdataFolder = new File(ess.getDataFolder(), "userdata"); if (!userdataFolder.exists() || !userdataFolder.isDirectory()) { @@ -241,13 +239,13 @@ public void convertStupidCamelCaseUserdataKeys() { } config.blockingSave(); } catch (final RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); throw ex; } } doneFile.setProperty("updateUsersStupidLegacyPathNames", true); doneFile.save(); - LOGGER.info("Done converting legacy userdata keys to Configurate."); + ess.getLogger().info("Done converting legacy userdata keys to Configurate."); } /** @@ -290,31 +288,31 @@ public void purgeBrokenNpcAccounts() { } final File backupFolder = new File(ess.getDataFolder(), "userdata-npc-backup"); if (backupFolder.exists()) { - LOGGER.info("NPC backup folder already exists; skipping NPC purge."); - LOGGER.info("To finish purging broken NPC accounts, rename the \"plugins/Essentials/userdata-npc-backup\" folder and restart your server."); + ess.getLogger().info("NPC backup folder already exists; skipping NPC purge."); + ess.getLogger().info("To finish purging broken NPC accounts, rename the \"plugins/Essentials/userdata-npc-backup\" folder and restart your server."); return; } else if (!backupFolder.mkdir()) { - LOGGER.info("Skipping NPC purge due to error creating backup folder."); + ess.getLogger().info("Skipping NPC purge due to error creating backup folder."); return; } - LOGGER.info("#===========================================================================#"); - LOGGER.info(" EssentialsX will now purge any NPC accounts which were incorrectly created."); - LOGGER.info(" Only NPC accounts with the default starting balance will be deleted. If"); - LOGGER.info(" they turn out to be valid NPC accounts, they will be re-created as needed."); - LOGGER.info(" Any files deleted here will be backed up to the "); - LOGGER.info(" \"plugins/Essentials/userdata-npc-backup\" folder. If you notice any files"); - LOGGER.info(" have been purged incorrectly, you should restore it from the backup and"); - LOGGER.info(" report it to us on GitHub:"); - LOGGER.info(" https://github.com/EssentialsX/Essentials/issues/new/choose"); - LOGGER.info(""); - LOGGER.info(" NOTE: This is a one-time process and will take several minutes if you have"); - LOGGER.info(" a lot of userdata files! If you interrupt this process, EssentialsX will"); - LOGGER.info(" skip the process until you rename or remove the backup folder."); - LOGGER.info("#===========================================================================#"); + ess.getLogger().info("#===========================================================================#"); + ess.getLogger().info(" EssentialsX will now purge any NPC accounts which were incorrectly created."); + ess.getLogger().info(" Only NPC accounts with the default starting balance will be deleted. If"); + ess.getLogger().info(" they turn out to be valid NPC accounts, they will be re-created as needed."); + ess.getLogger().info(" Any files deleted here will be backed up to the "); + ess.getLogger().info(" \"plugins/Essentials/userdata-npc-backup\" folder. If you notice any files"); + ess.getLogger().info(" have been purged incorrectly, you should restore it from the backup and"); + ess.getLogger().info(" report it to us on GitHub:"); + ess.getLogger().info(" https://github.com/EssentialsX/Essentials/issues/new/choose"); + ess.getLogger().info(""); + ess.getLogger().info(" NOTE: This is a one-time process and will take several minutes if you have"); + ess.getLogger().info(" a lot of userdata files! If you interrupt this process, EssentialsX will"); + ess.getLogger().info(" skip the process until you rename or remove the backup folder."); + ess.getLogger().info("#===========================================================================#"); final int totalUserFiles = userFiles.length; - LOGGER.info("Found ~" + totalUserFiles + " files under \"plugins/Essentials/userdata\"..."); + ess.getLogger().info("Found ~" + totalUserFiles + " files under \"plugins/Essentials/userdata\"..."); final AtomicInteger movedAccounts = new AtomicInteger(0); final AtomicInteger totalAccounts = new AtomicInteger(0); @@ -324,7 +322,7 @@ public void purgeBrokenNpcAccounts() { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); final ScheduledFuture feedbackTask = executor.scheduleWithFixedDelay( - () -> LOGGER.info("Scanned " + totalAccounts.get() + "/" + totalUserFiles + " accounts; moved " + movedAccounts.get() + " accounts"), + () -> ess.getLogger().info("Scanned " + totalAccounts.get() + "/" + totalUserFiles + " accounts; moved " + movedAccounts.get() + " accounts"), 5, feedbackInterval, TimeUnit.SECONDS); for (final File file : userFiles) { @@ -358,10 +356,10 @@ public void purgeBrokenNpcAccounts() { Files.move(file, new File(backupFolder, file.getName())); movedAccounts.incrementAndGet(); } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Error while moving NPC file", e); + ess.getLogger().log(Level.SEVERE, "Error while moving NPC file", e); } } catch (final RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); feedbackTask.cancel(false); executor.shutdown(); throw ex; @@ -372,18 +370,18 @@ public void purgeBrokenNpcAccounts() { doneFile.setProperty("updatePurgeBrokenNpcAccounts", true); doneFile.save(); - LOGGER.info("#===========================================================================#"); - LOGGER.info(" EssentialsX has finished purging NPC accounts."); - LOGGER.info(""); - LOGGER.info(" Deleted accounts: " + movedAccounts); - LOGGER.info(" Total accounts processed: " + totalAccounts); - LOGGER.info(""); - LOGGER.info(" Purged accounts have been backed up to"); - LOGGER.info(" \"plugins/Essentials/userdata-npc-backup\", and can be restored from there"); - LOGGER.info(" if needed. Please report any files which have been incorrectly deleted"); - LOGGER.info(" to us on GitHub:"); - LOGGER.info(" https://github.com/EssentialsX/Essentials/issues/new/choose"); - LOGGER.info("#===========================================================================#"); + ess.getLogger().info("#===========================================================================#"); + ess.getLogger().info(" EssentialsX has finished purging NPC accounts."); + ess.getLogger().info(""); + ess.getLogger().info(" Deleted accounts: " + movedAccounts); + ess.getLogger().info(" Total accounts processed: " + totalAccounts); + ess.getLogger().info(""); + ess.getLogger().info(" Purged accounts have been backed up to"); + ess.getLogger().info(" \"plugins/Essentials/userdata-npc-backup\", and can be restored from there"); + ess.getLogger().info(" if needed. Please report any files which have been incorrectly deleted"); + ess.getLogger().info(" to us on GitHub:"); + ess.getLogger().info(" https://github.com/EssentialsX/Essentials/issues/new/choose"); + ess.getLogger().info("#===========================================================================#"); } public void convertIgnoreList() { @@ -392,7 +390,7 @@ public void convertIgnoreList() { return; } - LOGGER.info("Attempting to migrate ignore list to UUIDs"); + ess.getLogger().info("Attempting to migrate ignore list to UUIDs"); final File userdataFolder = new File(ess.getDataFolder(), "userdata"); if (!userdataFolder.exists() || !userdataFolder.isDirectory()) { @@ -414,7 +412,7 @@ public void convertIgnoreList() { continue; } if (pattern.matcher(name.trim()).matches()) { - LOGGER.info("Detected already migrated ignore list!"); + ess.getLogger().info("Detected already migrated ignore list!"); return; } final User user = ess.getOfflineUser(name); @@ -427,13 +425,13 @@ public void convertIgnoreList() { config.blockingSave(); } } catch (final RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); throw ex; } } doneFile.setProperty("updateUsersIgnoreListUUID", true); doneFile.save(); - LOGGER.info("Done converting ignore list."); + ess.getLogger().info("Done converting ignore list."); } public void convertKits() { @@ -443,25 +441,25 @@ public void convertKits() { return; } - LOGGER.info("Attempting to convert old kits in config.yml to new kits.yml"); + ess.getLogger().info("Attempting to convert old kits in config.yml to new kits.yml"); final CommentedConfigurationNode section = ess.getSettings().getKitSection(); if (section == null) { - LOGGER.info("No kits found to migrate."); + ess.getLogger().info("No kits found to migrate."); return; } final Map legacyKits = ConfigurateUtil.getRawMap(section); for (final Map.Entry entry : legacyKits.entrySet()) { - LOGGER.info("Converting " + entry.getKey()); + ess.getLogger().info("Converting " + entry.getKey()); config.setRaw("kits." + entry.getKey(), entry.getValue()); } config.save(); doneFile.setProperty("kitsyml", true); doneFile.save(); - LOGGER.info("Done converting kits."); + ess.getLogger().info("Done converting kits."); } private void moveMotdRulesToFile(final String name) { @@ -494,7 +492,7 @@ private void moveMotdRulesToFile(final String name) { doneFile.setProperty("move" + name + "ToFile", true); doneFile.save(); } catch (final IOException e) { - LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e); + ess.getLogger().log(Level.SEVERE, tl("upgradingFilesError"), e); } } @@ -572,7 +570,7 @@ private void updateUsersPowerToolsFormat() { config.blockingSave(); } } catch (final RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); throw ex; } } @@ -628,7 +626,7 @@ private void updateUsersHomesFormat() { } } catch (final RuntimeException ex) { - LOGGER.log(Level.INFO, "File: " + file); + ess.getLogger().log(Level.INFO, "File: " + file); throw ex; } } @@ -657,15 +655,15 @@ private void sanitizeAllUserFilenames() { final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp"); final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename); if (!listOfFile.renameTo(tmpFile)) { - LOGGER.log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename)); + ess.getLogger().log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename)); continue; } if (newFile.exists()) { - LOGGER.log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename)); + ess.getLogger().log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename)); continue; } if (!tmpFile.renameTo(newFile)) { - LOGGER.log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); + ess.getLogger().log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); } } doneFile.setProperty("sanitizeAllUserFilenames", true); @@ -722,7 +720,7 @@ private void deleteOldItemsCsv() { doneFile.setProperty("deleteOldItemsCsv", true); doneFile.save(); } catch (final IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } } @@ -748,7 +746,7 @@ private void updateSpawnsToNewSpawnsConfig() { config.blockingSave(); } } catch (final Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } doneFile.setProperty("updateSpawnsToNewSpawnsConfig", true); @@ -776,7 +774,7 @@ private void updateJailsToNewJailsConfig() { config.blockingSave(); } } catch (final Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } doneFile.setProperty("updateJailsToNewJailsConfig", true); diff --git a/Essentials/src/main/java/com/earth2me/essentials/I18n.java b/Essentials/src/main/java/com/earth2me/essentials/I18n.java index 9a2e1e4e7af..ed30d66cc02 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/I18n.java +++ b/Essentials/src/main/java/com/earth2me/essentials/I18n.java @@ -21,7 +21,6 @@ import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; public class I18n implements net.ess3.api.II18n { @@ -89,7 +88,7 @@ private String translate(final String string) { } } catch (final MissingResourceException ex) { if (ess == null || ess.getSettings().isDebug()) { - Logger.getLogger("Essentials").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex); + ess.getLogger().log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex); } return defaultBundle.getString(string); } @@ -126,7 +125,7 @@ public void updateLocale(final String loc) { } ResourceBundle.clearCache(); messageFormatCache = new HashMap<>(); - Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); + ess.getLogger().log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); try { localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new UTF8PropertiesControl()); diff --git a/Essentials/src/main/java/com/earth2me/essentials/Jails.java b/Essentials/src/main/java/com/earth2me/essentials/Jails.java index c40c9959eae..2cbf2c91c7e 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Jails.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Jails.java @@ -34,12 +34,10 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class Jails implements net.ess3.api.IJails { - private static final transient Logger LOGGER = Logger.getLogger("Essentials"); private static transient boolean enabled = false; private final IEssentials ess; private final EssentialsConfiguration config; @@ -76,7 +74,7 @@ private void registerListeners() { final JailListener blockListener = new JailListener(); pluginManager.registerEvents(blockListener, ess); if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, "Registering Jail listener"); + ess.getLogger().log(Level.INFO, "Registering Jail listener"); } } @@ -268,9 +266,9 @@ public void onJailPlayerRespawn(final PlayerRespawnEvent event) { event.setRespawnLocation(getJail(user.getJail())); } catch (final Exception ex) { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); } else { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); } } } @@ -286,9 +284,9 @@ public void onJailPlayerTeleport(final PlayerTeleportEvent event) { event.setTo(getJail(user.getJail())); } catch (final Exception ex) { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); } else { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); } } user.sendMessage(tl("jailMessage")); @@ -306,9 +304,9 @@ public void onJailPlayerJoin(final PlayerJoinEvent event) { final CompletableFuture future = new CompletableFuture<>(); future.exceptionally(ex -> { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); } else { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); } return false; }); diff --git a/Essentials/src/main/java/com/earth2me/essentials/ManagedFile.java b/Essentials/src/main/java/com/earth2me/essentials/ManagedFile.java index 3d1fda60b70..b529445b6d6 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/ManagedFile.java +++ b/Essentials/src/main/java/com/earth2me/essentials/ManagedFile.java @@ -1,7 +1,6 @@ package com.earth2me.essentials; import net.ess3.api.IEssentials; -import org.bukkit.Bukkit; import java.io.BufferedInputStream; import java.io.BufferedReader; @@ -38,7 +37,7 @@ public ManagedFile(final String filename, final IEssentials ess) { throw new IOException("Could not delete file " + file.toString()); } } catch (final IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + Essentials.getWrappedLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -46,7 +45,7 @@ public ManagedFile(final String filename, final IEssentials ess) { try { copyResourceAscii("/" + filename, file); } catch (final IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex); + Essentials.getWrappedLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex); } } } @@ -113,7 +112,7 @@ public static boolean checkForVersion(final File file, final String version) thr if (correct.equals(test)) { return true; } else { - Bukkit.getLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually."); + Essentials.getWrappedLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually."); } } } @@ -147,7 +146,7 @@ public List getLines() { return lines; } } catch (final IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + Essentials.getWrappedLogger().log(Level.SEVERE, ex.getMessage(), ex); return Collections.emptyList(); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/Mob.java b/Essentials/src/main/java/com/earth2me/essentials/Mob.java index 514fc7b091c..11f51b41d80 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Mob.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Mob.java @@ -13,7 +13,6 @@ import java.util.Map; import java.util.Set; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; @@ -112,7 +111,6 @@ public enum Mob { CHEST_BOAT("ChestBoat", Enemies.NEUTRAL, "CHEST_BOAT"), ; - public static final Logger logger = Logger.getLogger("Essentials"); private static final Map hashMap = new HashMap<>(); private static final Map bukkitMap = new HashMap<>(); @@ -171,7 +169,7 @@ public static Mob fromBukkitType(final EntityType type) { public Entity spawn(final World world, final Server server, final Location loc) throws MobException { final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass()); if (entity == null) { - logger.log(Level.WARNING, tl("unableToSpawnMob")); + Essentials.getWrappedLogger().log(Level.WARNING, tl("unableToSpawnMob")); throw new MobException(); } return entity; diff --git a/Essentials/src/main/java/com/earth2me/essentials/MobData.java b/Essentials/src/main/java/com/earth2me/essentials/MobData.java index 16064005940..43d09afe664 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/MobData.java +++ b/Essentials/src/main/java/com/earth2me/essentials/MobData.java @@ -35,7 +35,6 @@ import java.util.List; import java.util.Locale; import java.util.Random; -import java.util.logging.Logger; import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; @@ -202,7 +201,6 @@ public enum MobData { COLD_FROG("cold", MobCompat.FROG, "frog:COLD", true), ; - public static final Logger logger = Logger.getLogger("Essentials"); final private String nickname; final private List suggestions; final private Object type; @@ -416,7 +414,7 @@ public void setData(final Entity spawned, final Player target, final String rawD } } } else { - logger.warning("Unknown mob data type: " + this.toString()); + Essentials.getWrappedLogger().warning("Unknown mob data type: " + this.toString()); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/Settings.java b/Essentials/src/main/java/com/earth2me/essentials/Settings.java index d9aae83fbeb..c0b1c618245 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Settings.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Settings.java @@ -40,14 +40,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static com.earth2me.essentials.I18n.tl; public class Settings implements net.ess3.api.ISettings { - private static final Logger logger = Logger.getLogger("Essentials"); private static final BigDecimal DEFAULT_MAX_MONEY = new BigDecimal("10000000000000"); private static final BigDecimal DEFAULT_MIN_MONEY = new BigDecimal("-10000000000000"); private final transient EssentialsConfiguration config; @@ -686,7 +684,7 @@ public void reloadConfig() { boolean mapModified = false; if (!disabledBukkitCommands.isEmpty()) { if (isDebug()) { - logger.log(Level.INFO, "Re-adding " + disabledBukkitCommands.size() + " disabled commands!"); + ess.getLogger().log(Level.INFO, "Re-adding " + disabledBukkitCommands.size() + " disabled commands!"); } ess.getKnownCommandsProvider().getKnownCommands().putAll(disabledBukkitCommands); disabledBukkitCommands.clear(); @@ -698,12 +696,12 @@ public void reloadConfig() { final Command toDisable = ess.getPluginCommand(effectiveAlias); if (toDisable != null) { if (isDebug()) { - logger.log(Level.INFO, "Attempting removal of " + effectiveAlias); + ess.getLogger().log(Level.INFO, "Attempting removal of " + effectiveAlias); } final Command removed = ess.getKnownCommandsProvider().getKnownCommands().remove(effectiveAlias); if (removed != null) { if (isDebug()) { - logger.log(Level.INFO, "Adding command " + effectiveAlias + " to disabled map!"); + ess.getLogger().log(Level.INFO, "Adding command " + effectiveAlias + " to disabled map!"); } disabledBukkitCommands.put(effectiveAlias, removed); } @@ -720,7 +718,7 @@ public void reloadConfig() { if (mapModified) { if (isDebug()) { - logger.log(Level.INFO, "Syncing commands"); + ess.getLogger().log(Level.INFO, "Syncing commands"); } if (reloadCount.get() < 2) { ess.scheduleSyncDelayedTask(() -> ess.getSyncCommandsProvider().syncCommands()); @@ -799,7 +797,7 @@ private List _getItemSpawnBlacklist() { //noinspection deprecation final IItemDb itemDb = ess.getItemDb(); if (itemDb == null || !itemDb.isReady()) { - logger.log(Level.FINE, "Skipping item spawn blacklist read; item DB not yet loaded."); + ess.getLogger().log(Level.FINE, "Skipping item spawn blacklist read; item DB not yet loaded."); return epItemSpwn; } for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) { @@ -811,7 +809,7 @@ private List _getItemSpawnBlacklist() { final ItemStack iStack = itemDb.get(itemName); epItemSpwn.add(iStack.getType()); } catch (final Exception ex) { - logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex); + ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex); } } return epItemSpwn; @@ -839,7 +837,7 @@ private List _getEnabledSigns() { try { newSigns.add(Signs.valueOf(signName).getSign()); } catch (final Exception ex) { - logger.log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); + ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); continue; } signsEnabled = true; @@ -953,7 +951,7 @@ public List getProtectList(final String configName) { } if (mat == null) { - logger.log(Level.SEVERE, tl("unknownItemInList", itemName, configName)); + ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, configName)); } else { list.add(mat); } @@ -1695,7 +1693,7 @@ private List _getUnprotectedSign() { try { newSigns.add(Signs.valueOf(signName).getSign()); } catch (final Exception ex) { - logger.log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names")); + ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names")); } } return newSigns; @@ -1880,7 +1878,7 @@ private Set> _getNickBlacklist() { try { blacklist.add(Pattern.compile(entry).asPredicate()); } catch (final PatternSyntaxException e) { - logger.warning("Invalid nickname blacklist regex: " + entry); + ess.getLogger().warning("Invalid nickname blacklist regex: " + entry); } }); diff --git a/Essentials/src/main/java/com/earth2me/essentials/Trade.java b/Essentials/src/main/java/com/earth2me/essentials/Trade.java index aa595a0bae3..7d241658c3d 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Trade.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Trade.java @@ -22,7 +22,6 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; @@ -80,7 +79,7 @@ public static void log(final String type, final String subtype, final String eve try { fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true); } catch (final IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + Essentials.getWrappedLogger().log(Level.SEVERE, null, ex); } } final StringBuilder sb = new StringBuilder(); @@ -159,7 +158,7 @@ public static void log(final String type, final String subtype, final String eve fw.write(sb.toString()); fw.flush(); } catch (final IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + Essentials.getWrappedLogger().log(Level.SEVERE, null, ex); } } @@ -168,7 +167,7 @@ public static void closeLog() { try { fw.close(); } catch (final IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + Essentials.getWrappedLogger().log(Level.SEVERE, null, ex); } fw = null; } diff --git a/Essentials/src/main/java/com/earth2me/essentials/UUIDMap.java b/Essentials/src/main/java/com/earth2me/essentials/UUIDMap.java index be24d8f9983..54385a512fb 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/UUIDMap.java +++ b/Essentials/src/main/java/com/earth2me/essentials/UUIDMap.java @@ -1,7 +1,6 @@ package com.earth2me.essentials; import com.google.common.io.Files; -import org.bukkit.Bukkit; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -90,7 +89,7 @@ public void loadAllUsers(final ConcurrentSkipListMap names, final } loading = false; } catch (final IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + Essentials.getWrappedLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -147,9 +146,9 @@ public void run() { Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv")); } } catch (final Exception ex2) { - Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2); + Essentials.getWrappedLogger().log(Level.SEVERE, ex2.getMessage(), ex2); } - Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); + Essentials.getWrappedLogger().log(Level.WARNING, ex.getMessage(), ex); } } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/User.java b/Essentials/src/main/java/com/earth2me/essentials/User.java index 5b6327fc686..8a8e71b67f7 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/User.java +++ b/Essentials/src/main/java/com/earth2me/essentials/User.java @@ -48,13 +48,11 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class User extends UserData implements Comparable, IMessageRecipient, net.ess3.api.IUser { private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK"); - private static final Logger logger = Logger.getLogger("Essentials"); // User modules private final IMessageRecipient messageRecipient; @@ -520,7 +518,7 @@ public void setDisplayNick() { this.getBase().setPlayerListName(name); } catch (final IllegalArgumentException e) { if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); + ess.getLogger().log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); } } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/Warps.java b/Essentials/src/main/java/com/earth2me/essentials/Warps.java index 6c34493b383..e1b441ee064 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/Warps.java +++ b/Essentials/src/main/java/com/earth2me/essentials/Warps.java @@ -16,12 +16,10 @@ import java.util.Map; import java.util.UUID; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class Warps implements IConf, net.ess3.api.IWarps { - private static final Logger logger = Logger.getLogger("Essentials"); private final Map warpPoints = new HashMap<>(); private final File warpsFolder; @@ -135,7 +133,7 @@ public final void reloadConfig() { warpPoints.put(new StringIgnoreCase(name), conf); } } catch (final Exception ex) { - logger.log(Level.WARNING, tl("loadWarpError", filename), ex); + Essentials.getWrappedLogger().log(Level.WARNING, tl("loadWarpError", filename), ex); } } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/api/Economy.java b/Essentials/src/main/java/com/earth2me/essentials/api/Economy.java index dd7ae19f71c..a848d70074a 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/api/Economy.java +++ b/Essentials/src/main/java/com/earth2me/essentials/api/Economy.java @@ -17,14 +17,12 @@ import java.text.MessageFormat; import java.util.UUID; import java.util.logging.Level; -import java.util.logging.Logger; /** * You should use Vault instead of directly using this class. */ public class Economy { public static final MathContext MATH_CONTEXT = MathContext.DECIMAL128; - private static final Logger LOGGER = Logger.getLogger("Essentials"); private static IEssentials ess; private static final String WARN_CALL_BEFORE_LOAD = "Essentials API is called before Essentials is loaded."; @@ -54,8 +52,8 @@ private static void createNPCFile(String name) { final UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); final File npcFile = new File(folder, npcUUID + ".yml"); if (npcFile.exists()) { - LOGGER.log(Level.SEVERE, MessageFormat.format(WARN_NPC_RECREATE_1, name, npcUUID.toString()), new RuntimeException()); - LOGGER.log(Level.SEVERE, WARN_NPC_RECREATE_2); + ess.getLogger().log(Level.SEVERE, MessageFormat.format(WARN_NPC_RECREATE_1, name, npcUUID.toString()), new RuntimeException()); + ess.getLogger().log(Level.SEVERE, WARN_NPC_RECREATE_2); } final EssentialsUserConfiguration npcConfig = new EssentialsUserConfiguration(name, npcUUID, npcFile); npcConfig.load(); @@ -90,7 +88,7 @@ private static User getUserByName(final String name) { if (player != null) { user = ess.getUser(player.getUniqueId()); if (user != null) { - LOGGER.log(Level.INFO, MessageFormat.format(WARN_PLAYER_UUID_NO_NAME, name, player.getUniqueId().toString()), new RuntimeException()); + ess.getLogger().log(Level.INFO, MessageFormat.format(WARN_PLAYER_UUID_NO_NAME, name, player.getUniqueId().toString()), new RuntimeException()); } } } @@ -190,7 +188,7 @@ public static void setMoney(final String name, final double balance) throws User try { setMoney(name, BigDecimal.valueOf(balance)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e); } } @@ -268,7 +266,7 @@ public static void add(final String name, final double amount) throws UserDoesNo try { add(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e); } } @@ -340,7 +338,7 @@ public static void subtract(final String name, final double amount) throws UserD try { substract(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to subtract " + amount + " of balance of " + name + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to subtract " + amount + " of balance of " + name + ": " + e.getMessage(), e); } } @@ -410,7 +408,7 @@ public static void divide(final String name, final double amount) throws UserDoe try { divide(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e); } } @@ -482,7 +480,7 @@ public static void multiply(final String name, final double amount) throws UserD try { multiply(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e); } } @@ -603,7 +601,7 @@ public static boolean hasEnough(final String name, final double amount) throws U try { return hasEnough(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } @@ -664,7 +662,7 @@ public static boolean hasMore(final String name, final double amount) throws Use try { return hasMore(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } @@ -726,7 +724,7 @@ public static boolean hasLess(final String name, final double amount) throws Use try { return hasLess(name, BigDecimal.valueOf(amount)); } catch (final ArithmeticException e) { - LOGGER.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } @@ -833,7 +831,7 @@ public static String format(final double amount) { try { return format(BigDecimal.valueOf(amount)); } catch (final NumberFormatException e) { - LOGGER.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e); + ess.getLogger().log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e); return "NaN"; } } @@ -900,7 +898,7 @@ public static boolean createNPC(final String name) { createNPCFile(name); return true; } - LOGGER.log(Level.WARNING, MessageFormat.format(WARN_EXISTING_NPC_CREATE, name, user.getConfigUUID()), new RuntimeException()); + ess.getLogger().log(Level.WARNING, MessageFormat.format(WARN_EXISTING_NPC_CREATE, name, user.getConfigUUID()), new RuntimeException()); return false; } diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandessentials.java index 9dd3fdd6087..5977ea6a787 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandessentials.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandessentials.java @@ -412,7 +412,7 @@ private void runNya(final Server server, final CommandSource sender, final Strin private void runMoo(final Server server, final CommandSource sender, final String command, final String[] args) { if (args.length == 2 && args[1].equals("moo")) { for (final String s : CONSOLE_MOO) { - logger.info(s); + ess.getLogger().info(s); } for (final Player player : ess.getOnlinePlayers()) { player.sendMessage(PLAYER_MOO); diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandgc.java index 4a9d1cbb00e..5f7392cdea3 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandgc.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandgc.java @@ -3,7 +3,6 @@ import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Server; @@ -57,7 +56,7 @@ protected void run(final Server server, final CommandSource sender, final String tileEntities += chunk.getTileEntities().length; } } catch (final java.lang.ClassCastException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); + ess.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); } sender.sendMessage(tl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities)); diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandsell.java index 1a153c03982..f9cd09bf508 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandsell.java @@ -117,7 +117,7 @@ private BigDecimal sellItem(final User user, final ItemStack is, final String[] Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(result, ess), user.getLocation(), user.getMoney(), ess); user.giveMoney(result, null, UserBalanceUpdateEvent.Cause.COMMAND_SELL); user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(result, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess))); - logger.log(Level.INFO, tl("itemSoldConsole", user.getName(), is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess), user.getDisplayName())); + ess.getLogger().log(Level.INFO, tl("itemSoldConsole", user.getName(), is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess), user.getDisplayName())); return result; } diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpaccept.java index cabdeb8cae9..f97a8faf4d7 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpaccept.java @@ -99,7 +99,7 @@ private void handleTeleport(final User user, final IUser.TpaRequest request, Str Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { if (ess.getSettings().isDebug()) { - logger.info("TPA accept cancelled by API for " + user.getName() + " (requested by " + requester.getName() + ")"); + ess.getLogger().info("TPA accept cancelled by API for " + user.getName() + " (requested by " + requester.getName() + ")"); } return; } diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpdeny.java index b5c10de5109..7c1877e0319 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpdeny.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtpdeny.java @@ -84,7 +84,7 @@ private boolean sendEvent(User user, User player, IUser.TpaRequest request) { Bukkit.getPluginManager().callEvent(event); final boolean cancelled = event.isCancelled(); if (cancelled && ess.getSettings().isDebug()) { - logger.info("TPA deny cancelled by API for " + user.getName() + " (requested by " + player.getName() + ")"); + ess.getLogger().info("TPA deny cancelled by API for " + user.getName() + " (requested by " + player.getName() + ")"); } return event.isCancelled(); } diff --git a/Essentials/src/main/java/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/main/java/com/earth2me/essentials/commands/EssentialsCommand.java index 7fcfdea88b4..8418dcfd335 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/commands/EssentialsCommand.java +++ b/Essentials/src/main/java/com/earth2me/essentials/commands/EssentialsCommand.java @@ -26,14 +26,12 @@ import java.util.MissingResourceException; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; public abstract class EssentialsCommand implements IEssentialsCommand { - protected static final Logger logger = Logger.getLogger("Essentials"); /** * Common time durations (in seconds), for use in tab completion. */ @@ -334,7 +332,7 @@ protected final List tabCompleteCommand(final CommandSource sender, fina public void showError(final CommandSender sender, final Throwable throwable, final String commandLabel) { sender.sendMessage(tl("errorWithMessage", throwable.getMessage())); if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, tl("errorCallingCommand", commandLabel), throwable); + ess.getLogger().log(Level.INFO, tl("errorCallingCommand", commandLabel), throwable); throwable.printStackTrace(); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/config/ConfigurationSaveTask.java b/Essentials/src/main/java/com/earth2me/essentials/config/ConfigurationSaveTask.java index 6c9ebc51ca7..b6d4c7461b9 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/config/ConfigurationSaveTask.java +++ b/Essentials/src/main/java/com/earth2me/essentials/config/ConfigurationSaveTask.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.config; +import com.earth2me.essentials.Essentials; import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.ConfigurateException; import org.spongepowered.configurate.yaml.YamlConfigurationLoader; @@ -7,8 +8,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; -import static com.earth2me.essentials.config.EssentialsConfiguration.LOGGER; - public class ConfigurationSaveTask implements Runnable { private final YamlConfigurationLoader loader; private final CommentedConfigurationNode node; @@ -32,7 +31,7 @@ public void run() { try { loader.save(node); } catch (ConfigurateException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } finally { pendingWrites.decrementAndGet(); } diff --git a/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsConfiguration.java b/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsConfiguration.java index 1e9988a5378..9e2eb89edbb 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsConfiguration.java +++ b/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsConfiguration.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.config; +import com.earth2me.essentials.Essentials; import com.earth2me.essentials.config.annotations.DeleteIfIncomplete; import com.earth2me.essentials.config.annotations.DeleteOnEmpty; import com.earth2me.essentials.config.entities.CommandCooldown; @@ -44,12 +45,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class EssentialsConfiguration { - protected static final Logger LOGGER = Logger.getLogger("Essentials"); private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); private static final ObjectMapper.Factory MAPPER_FACTORY = ObjectMapper.factoryBuilder() .addProcessor(DeleteOnEmpty.class, (data, value) -> new DeleteOnEmptyProcessor()) @@ -133,7 +132,7 @@ public Map getLocationSectionMap(final String path) { try { result.put(entry.getKey().toLowerCase(Locale.ENGLISH), jailNode.get(LazyLocation.class)); } catch (SerializationException e) { - LOGGER.log(Level.WARNING, "Error serializing key " + entry.getKey(), e); + Essentials.getWrappedLogger().log(Level.WARNING, "Error serializing key " + entry.getKey(), e); } } return result; @@ -147,7 +146,7 @@ public void setExplicitList(final String path, final List list, final Typ try { toSplitRoot(path, configurationNode).set(type, list); } catch (SerializationException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } } @@ -163,7 +162,7 @@ public List getList(final String path, Class type) { } return list; } catch (SerializationException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); return new ArrayList<>(); } } @@ -301,7 +300,7 @@ public void removeProperty(String path) { try { node.set(null); } catch (SerializationException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } } } @@ -310,7 +309,7 @@ private void setInternal(final String path, final Object value) { try { toSplitRoot(path, configurationNode).set(value); } catch (SerializationException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } } @@ -336,13 +335,13 @@ public CommentedConfigurationNode toSplitRoot(String path, final CommentedConfig public synchronized void load() { if (pendingWrites.get() != 0) { - LOGGER.log(Level.INFO, "Parsing config file {0} has been aborted due to {1} current pending write(s).", new Object[]{configFile, pendingWrites.get()}); + Essentials.getWrappedLogger().log(Level.INFO, "Parsing config file {0} has been aborted due to {1} current pending write(s).", new Object[]{configFile, pendingWrites.get()}); return; } if (configFile.getParentFile() != null && !configFile.getParentFile().exists()) { if (!configFile.getParentFile().mkdirs()) { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); + Essentials.getWrappedLogger().log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); return; } } @@ -354,10 +353,10 @@ public synchronized void load() { convertAltFile(); } else if (templateName != null) { try (final InputStream is = resourceClass.getResourceAsStream(templateName)) { - LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString())); + Essentials.getWrappedLogger().log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString())); Files.copy(is, configFile.toPath()); } catch (IOException e) { - LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), e); + Essentials.getWrappedLogger().log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), e); } } } @@ -367,12 +366,12 @@ public synchronized void load() { } catch (final ParsingException e) { final File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); if (configFile.renameTo(broken)) { - LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), e.getCause()); + Essentials.getWrappedLogger().log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), e.getCause()); return; } - LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken. A backup file has failed to be created", e.getCause()); + Essentials.getWrappedLogger().log(Level.SEVERE, "The file " + configFile.toString() + " is broken. A backup file has failed to be created", e.getCause()); } catch (final ConfigurateException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } finally { // Something is wrong! We need a node! I hope the backup worked! if (configurationNode == null) { @@ -435,7 +434,7 @@ public synchronized void blockingSave() { try { delaySave().get(); } catch (final InterruptedException | ExecutionException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); + Essentials.getWrappedLogger().log(Level.SEVERE, e.getMessage(), e); } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsUserConfiguration.java b/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsUserConfiguration.java index 798b4da3720..35d7c1e9008 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsUserConfiguration.java +++ b/Essentials/src/main/java/com/earth2me/essentials/config/EssentialsUserConfiguration.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.config; +import com.earth2me.essentials.Essentials; import com.google.common.base.Charsets; import com.google.common.io.Files; @@ -43,7 +44,7 @@ public void convertLegacyFile() { //noinspection UnstableApiUsage Files.move(file, new File(configFile.getParentFile(), uuid + ".yml")); } catch (final IOException ex) { - LOGGER.log(Level.WARNING, "Failed to migrate user: " + username, ex); + Essentials.getWrappedLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); } setProperty("last-account-name", username); @@ -68,7 +69,7 @@ public void convertAltFile() { //noinspection UnstableApiUsage Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml")); } catch (final IOException ex) { - LOGGER.log(Level.WARNING, "Failed to migrate user: " + username, ex); + Essentials.getWrappedLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); } } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/economy/vault/VaultEconomyProvider.java b/Essentials/src/main/java/com/earth2me/essentials/economy/vault/VaultEconomyProvider.java index 4ba9e66ca16..672256d690b 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/economy/vault/VaultEconomyProvider.java +++ b/Essentials/src/main/java/com/earth2me/essentials/economy/vault/VaultEconomyProvider.java @@ -19,7 +19,6 @@ import java.util.List; import java.util.UUID; import java.util.logging.Level; -import java.util.logging.Logger; /** * A goddamn Vault adapter, what more do you want? @@ -29,7 +28,6 @@ * {@link com.earth2me.essentials.User}. */ public class VaultEconomyProvider implements Economy { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private static final String WARN_NPC_RECREATE_1 = "Account creation was requested for NPC user {0}, but an account file with UUID {1} already exists."; private static final String WARN_NPC_RECREATE_2 = "Essentials will create a new account as requested by the other plugin, but this is almost certainly a bug and should be reported."; @@ -301,8 +299,8 @@ public boolean createPlayerAccount(OfflinePlayer player) { } final File npcFile = new File(folder, player.getUniqueId() + ".yml"); if (npcFile.exists()) { - LOGGER.log(Level.SEVERE, MessageFormat.format(WARN_NPC_RECREATE_1, player.getName(), player.getUniqueId().toString()), new RuntimeException()); - LOGGER.log(Level.SEVERE, WARN_NPC_RECREATE_2); + ess.getLogger().log(Level.SEVERE, MessageFormat.format(WARN_NPC_RECREATE_1, player.getName(), player.getUniqueId().toString()), new RuntimeException()); + ess.getLogger().log(Level.SEVERE, WARN_NPC_RECREATE_2); } final EssentialsUserConfiguration npcConfig = new EssentialsUserConfiguration(player.getName(), player.getUniqueId(), npcFile); npcConfig.load(); @@ -317,7 +315,7 @@ public boolean createPlayerAccount(OfflinePlayer player) { // Loading a v4 UUID that we somehow didn't track, mark it as a normal player and hope for the best, vault sucks :/ try { if (ess.getSettings().isDebug()) { - LOGGER.info("Vault requested a player account creation for a v4 UUID: " + player); + ess.getLogger().info("Vault requested a player account creation for a v4 UUID: " + player); } ess.getUserMap().load(player); return true; diff --git a/Essentials/src/main/java/com/earth2me/essentials/items/FlatItemDb.java b/Essentials/src/main/java/com/earth2me/essentials/items/FlatItemDb.java index b9c8cb80db7..e8edab47dd5 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/items/FlatItemDb.java +++ b/Essentials/src/main/java/com/earth2me/essentials/items/FlatItemDb.java @@ -23,13 +23,11 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Logger; import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; public class FlatItemDb extends AbstractItemDb { - protected static final Logger LOGGER = Logger.getLogger("Essentials"); private static final Gson gson = new Gson(); // Maps primary name to ItemData @@ -54,7 +52,7 @@ public void reloadConfig() { } this.rebuild(); - LOGGER.info(String.format("Loaded %s items from items.json.", listNames().size())); + ess.getLogger().info(String.format("Loaded %s items from items.json.", listNames().size())); } private void rebuild() { @@ -100,7 +98,7 @@ private void loadJSON(final String source) { if (valid) { allAliases.add(key); } else { - LOGGER.warning(String.format("Failed to add item: \"%s\": %s", key, element.toString())); + ess.getLogger().warning(String.format("Failed to add item: \"%s\": %s", key, element.toString())); } } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/items/LegacyItemDb.java b/Essentials/src/main/java/com/earth2me/essentials/items/LegacyItemDb.java index 5698fc9d7bd..4782449c3a6 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/items/LegacyItemDb.java +++ b/Essentials/src/main/java/com/earth2me/essentials/items/LegacyItemDb.java @@ -17,14 +17,12 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; public class LegacyItemDb extends AbstractItemDb { - protected static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient Map items = new HashMap<>(); private final transient Map> names = new HashMap<>(); private final transient Map primaryName = new HashMap<>(); @@ -119,7 +117,7 @@ public void reloadConfig() { nameList.sort(LengthCompare.INSTANCE); } - LOGGER.info(String.format("Loaded %s items from items.csv.", listNames().size())); + ess.getLogger().info(String.format("Loaded %s items from items.csv.", listNames().size())); ready = true; } diff --git a/Essentials/src/main/java/com/earth2me/essentials/signs/SignBlockListener.java b/Essentials/src/main/java/com/earth2me/essentials/signs/SignBlockListener.java index eba8079a7a9..5b238fe7aec 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/signs/SignBlockListener.java +++ b/Essentials/src/main/java/com/earth2me/essentials/signs/SignBlockListener.java @@ -23,10 +23,8 @@ import org.bukkit.event.block.SignChangeEvent; import java.util.logging.Level; -import java.util.logging.Logger; public class SignBlockListener implements Listener { - private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient IEssentials ess; public SignBlockListener(final IEssentials ess) { @@ -52,7 +50,7 @@ public boolean protectSignsAndBlocks(final Block block, final Player player) thr // prevent any signs be broken by destroying the block they are attached to if (EssentialsSign.checkIfBlockBreaksSigns(block)) { if (ess.getSettings().isDebug()) { - LOGGER.log(Level.INFO, "Prevented that a block was broken next to a sign."); + ess.getLogger().log(Level.INFO, "Prevented that a block was broken next to a sign."); } return true; } @@ -70,7 +68,7 @@ public boolean protectSignsAndBlocks(final Block block, final Player player) thr for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBreak(block, player, ess)) { - LOGGER.log(Level.INFO, "A block was protected by a sign."); + ess.getLogger().log(Level.INFO, "A block was protected by a sign."); return true; } } diff --git a/Essentials/src/main/java/com/earth2me/essentials/textreader/HelpInput.java b/Essentials/src/main/java/com/earth2me/essentials/textreader/HelpInput.java index dd3442c80b9..3fb835b8b72 100644 --- a/Essentials/src/main/java/com/earth2me/essentials/textreader/HelpInput.java +++ b/Essentials/src/main/java/com/earth2me/essentials/textreader/HelpInput.java @@ -15,12 +15,10 @@ import java.util.Locale; import java.util.Map; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class HelpInput implements IText { - private static final Logger logger = Logger.getLogger("Essentials"); private final transient List lines = new ArrayList<>(); private final transient List chapters = new ArrayList<>(); private final transient Map bookmarks = new HashMap<>(); @@ -121,7 +119,7 @@ public HelpInput(final User user, final String match, final IEssentials ess) { } catch (final NullPointerException ignored) { } catch (final Exception ex) { if (!reported) { - logger.log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex); + ess.getLogger().log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex); } reported = true; } diff --git a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java index 6a65eafcadb..445a686c2de 100644 --- a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java +++ b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.antibuild; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.metrics.MetricsWrapper; import org.bukkit.Material; import org.bukkit.plugin.Plugin; @@ -9,6 +10,7 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; +import java.util.logging.Logger; public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { private final transient Map settingsBoolean = new EnumMap<>(AntiBuildConfig.class); @@ -37,6 +39,16 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + @Override public boolean checkProtectionItems(final AntiBuildConfig list, final Material mat) { final List itemList = settingsList.get(list); diff --git a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java index 07f47153a27..92a0f5599f2 100644 --- a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java +++ b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java @@ -33,12 +33,10 @@ import org.bukkit.inventory.ItemStack; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class EssentialsAntiBuildListener implements Listener { - private static final Logger logger = Logger.getLogger("EssentialsAntiBuild"); final private transient IAntiBuild prot; final private transient IEssentials ess; @@ -65,7 +63,7 @@ private static boolean isEntityPickupEvent() { private boolean metaPermCheck(final User user, final String action, final Block block) { if (block == null) { if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, "AntiBuild permission check failed, invalid block."); + prot.getLogger().log(Level.INFO, "AntiBuild permission check failed, invalid block."); } return false; } @@ -78,7 +76,7 @@ private boolean metaPermCheck(final User user, final String action, final Block private boolean metaPermCheck(final User user, final String action, final ItemStack item) { if (item == null) { if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, "AntiBuild permission check failed, invalid item."); + prot.getLogger().log(Level.INFO, "AntiBuild permission check failed, invalid item."); } return false; } @@ -102,7 +100,7 @@ private boolean metaPermCheck(final User user, final String action, final Materi return user.isAuthorized(dataPerm); } else { if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, "DataValue perm on " + user.getName() + " is not directly set: " + dataPerm); + prot.getLogger().log(Level.INFO, "DataValue perm on " + user.getName() + " is not directly set: " + dataPerm); } } } diff --git a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsConnect.java b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsConnect.java index c6fa26c41b9..410da6a2c0d 100644 --- a/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsConnect.java +++ b/EssentialsAntiBuild/src/main/java/com/earth2me/essentials/antibuild/EssentialsConnect.java @@ -8,18 +8,16 @@ import org.bukkit.plugin.Plugin; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; class EssentialsConnect { - private static final Logger logger = Logger.getLogger("EssentialsAntiBuild"); private final transient IEssentials ess; private final transient IAntiBuild protect; EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) { if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) { - logger.log(Level.WARNING, tl("versionMismatchAll")); + essProtect.getLogger().log(Level.WARNING, tl("versionMismatchAll")); } ess = (IEssentials) essPlugin; protect = (IAntiBuild) essProtect; @@ -35,7 +33,7 @@ IEssentials getEssentials() { void alert(final User user, final String item, final String type) { final Location loc = user.getLocation(); final String warnMessage = tl("alertFormat", user.getName(), type, item, loc.getWorld().getName() + "," + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ()); - logger.log(Level.WARNING, warnMessage); + protect.getLogger().log(Level.WARNING, warnMessage); for (final Player p : ess.getServer().getOnlinePlayers()) { final User alertUser = ess.getUser(p); if (alertUser.isAuthorized("essentials.protect.alerts")) { diff --git a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChat.java index 374f407499a..341075888b6 100644 --- a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChat.java +++ b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChat.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.chat; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IEssentials; import org.bukkit.command.Command; @@ -12,6 +13,7 @@ import java.util.HashMap; import java.util.Map; import java.util.logging.Level; +import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; @@ -33,9 +35,9 @@ public void onEnable() { final Map chatStore = Collections.synchronizedMap(new HashMap<>()); - final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, chatStore); - final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, chatStore); - final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, chatStore); + final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, this, chatStore); + final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, this, chatStore); + final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, this, chatStore); pluginManager.registerEvents(playerListenerLowest, this); pluginManager.registerEvents(playerListenerNormal, this); pluginManager.registerEvents(playerListenerHighest, this); @@ -45,6 +47,16 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + @Override public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { metrics.markCommand(command.getName(), true); diff --git a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayer.java index 32988091a01..c3d991ac279 100644 --- a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayer.java @@ -9,16 +9,16 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; import java.util.Map; -import java.util.logging.Logger; public abstract class EssentialsChatPlayer implements Listener { - static final Logger logger = Logger.getLogger("EssentialsChat"); final transient IEssentials ess; + final transient EssentialsChat essChat; final transient Server server; private final transient Map chatStorage; - EssentialsChatPlayer(final Server server, final IEssentials ess, final Map chatStorage) { + EssentialsChatPlayer(final Server server, final IEssentials ess, final EssentialsChat essChat, final Map chatStorage) { this.ess = ess; + this.essChat = essChat; this.server = server; this.chatStorage = chatStorage; } diff --git a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java index f59436f1d4a..863c2ed65d1 100644 --- a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java +++ b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java @@ -9,8 +9,8 @@ import java.util.Map; public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer { - EssentialsChatPlayerListenerHighest(final Server server, final IEssentials ess, final Map chatStorage) { - super(server, ess, chatStorage); + EssentialsChatPlayerListenerHighest(final Server server, final IEssentials ess, final EssentialsChat essChat, final Map chatStorage) { + super(server, ess, essChat, chatStorage); } @EventHandler(priority = EventPriority.HIGHEST) diff --git a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java index 0032b35854d..8e113e8f6e9 100644 --- a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java +++ b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java @@ -15,8 +15,8 @@ import java.util.Map; public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer { - EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess, final Map chatStorage) { - super(server, ess, chatStorage); + EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess, final EssentialsChat essChat, final Map chatStorage) { + super(server, ess, essChat, chatStorage); } @EventHandler(priority = EventPriority.LOWEST) diff --git a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java index a216a1e7fb8..7726dbaca97 100644 --- a/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java +++ b/EssentialsChat/src/main/java/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java @@ -21,8 +21,8 @@ import static com.earth2me.essentials.I18n.tl; public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer { - EssentialsChatPlayerListenerNormal(final Server server, final IEssentials ess, final Map chatStorage) { - super(server, ess, chatStorage); + EssentialsChatPlayerListenerNormal(final Server server, final IEssentials ess, final EssentialsChat essChat, final Map chatStorage) { + super(server, ess, essChat, chatStorage); } @EventHandler(priority = EventPriority.NORMAL) @@ -88,7 +88,7 @@ public void onPlayerChat(final AsyncPlayerChatEvent event) { outList.add(event.getPlayer()); } catch (final UnsupportedOperationException ex) { if (ess.getSettings().isDebug()) { - logger.log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex); + essChat.getLogger().log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex); } return; } diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/EssentialsDiscord.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/EssentialsDiscord.java index fcc24e099ca..b2936a11ec3 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/EssentialsDiscord.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/EssentialsDiscord.java @@ -1,5 +1,6 @@ package net.essentialsx.discord; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.IEssentialsModule; import com.earth2me.essentials.metrics.MetricsWrapper; @@ -17,7 +18,6 @@ import static com.earth2me.essentials.I18n.tl; public class EssentialsDiscord extends JavaPlugin implements IEssentialsModule { - private final static Logger logger = Logger.getLogger("EssentialsDiscord"); private transient IEssentials ess; private transient MetricsWrapper metrics = null; @@ -39,7 +39,7 @@ public void onEnable() { // JDK-8274349 - Mitigation for a regression in Java 17 on 1 core systems which was fixed in 17.0.2 final String[] javaVersion = System.getProperty("java.version").split("\\."); if (Runtime.getRuntime().availableProcessors() <= 1 && javaVersion[0].startsWith("17") && (javaVersion.length < 2 || (javaVersion[1].equals("0") && javaVersion[2].startsWith("1")))) { - logger.log(Level.INFO, "Essentials is mitigating JDK-8274349"); + getLogger().log(Level.INFO, "Essentials is mitigating JDK-8274349"); System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1"); } @@ -58,7 +58,7 @@ public void onEnable() { jda.startup(); ess.scheduleSyncDelayedTask(() -> ((InteractionControllerImpl) jda.getInteractionController()).processBatchRegistration()); } catch (Exception e) { - logger.log(Level.SEVERE, tl("discordErrorLogin", e.getMessage())); + getLogger().log(Level.SEVERE, tl("discordErrorLogin", e.getMessage())); if (ess.getSettings().isDebug()) { e.printStackTrace(); } @@ -67,6 +67,25 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + + public static Logger getWrappedLogger() { + try { + return EssentialsLogger.getLoggerProvider("EssentialsDiscord"); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return Logger.getLogger("EssentialsDiscord"); + } + } + public void onReload() { if (jda != null && !jda.isInvalidStartup()) { jda.updatePresence(); diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/JDADiscordService.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/JDADiscordService.java index bc700670d82..a9057d9f6fb 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/JDADiscordService.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/JDADiscordService.java @@ -60,7 +60,7 @@ import static com.earth2me.essentials.I18n.tl; public class JDADiscordService implements DiscordService, IEssentialsModule { - private final static Logger logger = Logger.getLogger("EssentialsDiscord"); + private final static Logger logger = EssentialsDiscord.getWrappedLogger(); private final EssentialsDiscord plugin; private final Unsafe unsafe = this::getJda; diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionControllerImpl.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionControllerImpl.java index c5c9150bc31..2101544d8a3 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionControllerImpl.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionControllerImpl.java @@ -12,6 +12,7 @@ import net.essentialsx.api.v2.services.discord.InteractionController; import net.essentialsx.api.v2.services.discord.InteractionEvent; import net.essentialsx.api.v2.services.discord.InteractionException; +import net.essentialsx.discord.EssentialsDiscord; import net.essentialsx.discord.JDADiscordService; import net.essentialsx.discord.util.DiscordUtil; import org.jetbrains.annotations.NotNull; @@ -27,8 +28,7 @@ import static com.earth2me.essentials.I18n.tl; public class InteractionControllerImpl extends ListenerAdapter implements InteractionController { - private final static Logger logger = Logger.getLogger("EssentialsDiscord"); - + private static final Logger logger = EssentialsDiscord.getWrappedLogger(); private final JDADiscordService jda; private final Map commandMap = new ConcurrentHashMap<>(); diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionEventImpl.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionEventImpl.java index 37c6dfd405a..c6c60193444 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionEventImpl.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/interactions/InteractionEventImpl.java @@ -9,6 +9,7 @@ import net.essentialsx.api.v2.services.discord.InteractionChannel; import net.essentialsx.api.v2.services.discord.InteractionEvent; import net.essentialsx.api.v2.services.discord.InteractionMember; +import net.essentialsx.discord.EssentialsDiscord; import net.essentialsx.discord.util.DiscordUtil; import java.util.ArrayList; @@ -20,7 +21,7 @@ * A class which provides information about what triggered an interaction event. */ public class InteractionEventImpl implements InteractionEvent { - private final static Logger logger = Logger.getLogger("EssentialsDiscord"); + private final static Logger logger = EssentialsDiscord.getWrappedLogger(); private final SlashCommandEvent event; private final InteractionMember member; private final List replyBuffer = new ArrayList<>(); diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/listeners/DiscordListener.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/listeners/DiscordListener.java index bc227f8df0e..5f7a07d4a92 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/listeners/DiscordListener.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/listeners/DiscordListener.java @@ -10,6 +10,7 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.ess3.api.IUser; import net.essentialsx.api.v2.events.discord.DiscordRelayEvent; +import net.essentialsx.discord.EssentialsDiscord; import net.essentialsx.discord.JDADiscordService; import net.essentialsx.discord.interactions.InteractionChannelImpl; import net.essentialsx.discord.interactions.InteractionMemberImpl; @@ -25,7 +26,7 @@ import java.util.regex.Pattern; public class DiscordListener extends ListenerAdapter { - private final static Logger logger = Logger.getLogger("EssentialsDiscord"); + private final static Logger logger = EssentialsDiscord.getWrappedLogger(); private final JDADiscordService plugin; diff --git a/EssentialsDiscord/src/main/java/net/essentialsx/discord/util/ConsoleInjector.java b/EssentialsDiscord/src/main/java/net/essentialsx/discord/util/ConsoleInjector.java index 24c301c912e..977efb37b79 100644 --- a/EssentialsDiscord/src/main/java/net/essentialsx/discord/util/ConsoleInjector.java +++ b/EssentialsDiscord/src/main/java/net/essentialsx/discord/util/ConsoleInjector.java @@ -4,6 +4,7 @@ import com.google.common.base.Splitter; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.utils.TimeFormat; +import net.essentialsx.discord.EssentialsDiscord; import net.essentialsx.discord.JDADiscordService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LogEvent; @@ -21,7 +22,7 @@ @Plugin(name = "EssentialsX-ConsoleInjector", category = "Core", elementType = "appender", printObject = true) public class ConsoleInjector extends AbstractAppender { - private final static java.util.logging.Logger logger = java.util.logging.Logger.getLogger("EssentialsDiscord"); + private final static java.util.logging.Logger logger = EssentialsDiscord.getWrappedLogger(); private final JDADiscordService jda; private final BlockingQueue messageQueue = new LinkedBlockingQueue<>(); diff --git a/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIP.java index 8cf58ebb1ed..aa848de9216 100644 --- a/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIP.java +++ b/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIP.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.geoip; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IEssentials; import org.bukkit.plugin.PluginManager; @@ -28,7 +29,7 @@ public void onEnable() { Logger.getLogger(com.fasterxml.jackson.databind.ext.Java7Support.class.getName()).setLevel(Level.SEVERE); - final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess); + final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess, this); pm.registerEvents(playerListener, this); getLogger().log(Level.INFO, "This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/."); @@ -38,4 +39,14 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + } diff --git a/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java b/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java index 9bdbc30bdc5..a52c66b363c 100644 --- a/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java +++ b/EssentialsGeoIP/src/main/java/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java @@ -31,21 +31,21 @@ import java.util.Arrays; import java.util.Date; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import static com.earth2me.essentials.I18n.tl; public class EssentialsGeoIPPlayerListener implements Listener, IConf { - private static final Logger logger = Logger.getLogger("EssentialsGeoIP"); private final File dataFolder; private final EssentialsConfiguration config; private final transient IEssentials ess; + private final transient EssentialsGeoIP essGeo; private DatabaseReader mmreader = null; // initialize maxmind geoip2 reader private File databaseFile; - EssentialsGeoIPPlayerListener(final File dataFolder, final IEssentials ess) { + EssentialsGeoIPPlayerListener(final File dataFolder, final IEssentials ess, final EssentialsGeoIP essGeo) { this.ess = ess; + this.essGeo = essGeo; this.dataFolder = dataFolder; this.config = new EssentialsConfiguration(new File(dataFolder, "config.yml"), "/config.yml", EssentialsGeoIP.class); reloadConfig(); @@ -66,7 +66,7 @@ private void delayedJoin(final Player player) { final StringBuilder sb = new StringBuilder(); if (mmreader == null) { - logger.log(Level.WARNING, tl("geoIpErrorOnJoin", u.getName())); + essGeo.getLogger().log(Level.WARNING, tl("geoIpErrorOnJoin", u.getName())); return; } @@ -106,10 +106,10 @@ private void delayedJoin(final Player player) { } // GeoIP2 API forced this when address not found in their DB. jar will not complied without this. // TODO: Maybe, we can set a new custom msg about addr-not-found in messages.properties. - logger.log(Level.INFO, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); + essGeo.getLogger().log(Level.INFO, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); } catch (final IOException | GeoIp2Exception ex) { // GeoIP2 API forced this when address not found in their DB. jar will not complied without this. - logger.log(Level.SEVERE, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); + essGeo.getLogger().log(Level.SEVERE, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); } if (config.getBoolean("show-on-whois", true)) { u.setGeoLocation(sb.toString()); @@ -153,7 +153,7 @@ public final void reloadConfig() { if (config.getBoolean("database.download-if-missing", true)) { downloadDatabase(); } else { - logger.log(Level.SEVERE, tl("cantFindGeoIpDB")); + essGeo.getLogger().log(Level.SEVERE, tl("cantFindGeoIpDB")); return; } } else if (config.getBoolean("database.update.enable", true)) { @@ -177,7 +177,7 @@ public final void reloadConfig() { mmreader = new DatabaseReader.Builder(databaseFile).build(); } } catch (final IOException ex) { - logger.log(Level.SEVERE, tl("cantReadGeoIpDB"), ex); + essGeo.getLogger().log(Level.SEVERE, tl("cantReadGeoIpDB"), ex); } } @@ -190,16 +190,16 @@ private void downloadDatabase() { url = config.getString("database.download-url", null); } if (url == null || url.isEmpty()) { - logger.log(Level.SEVERE, tl("geoIpUrlEmpty")); + essGeo.getLogger().log(Level.SEVERE, tl("geoIpUrlEmpty")); return; } final String licenseKey = config.getString("database.license-key", ""); if (licenseKey == null || licenseKey.isEmpty()) { - logger.log(Level.SEVERE, tl("geoIpLicenseMissing")); + essGeo.getLogger().log(Level.SEVERE, tl("geoIpLicenseMissing")); return; } url = url.replace("{LICENSEKEY}", licenseKey); - logger.log(Level.INFO, tl("downloadingGeoIp")); + essGeo.getLogger().log(Level.INFO, tl("downloadingGeoIp")); final URL downloadUrl = new URL(url); final URLConnection conn = downloadUrl.openConnection(); conn.setConnectTimeout(10000); @@ -233,9 +233,9 @@ private void downloadDatabase() { output.close(); input.close(); } catch (final MalformedURLException ex) { - logger.log(Level.SEVERE, tl("geoIpUrlInvalid"), ex); + essGeo.getLogger().log(Level.SEVERE, tl("geoIpUrlInvalid"), ex); } catch (final IOException ex) { - logger.log(Level.SEVERE, tl("connectionFailed"), ex); + essGeo.getLogger().log(Level.SEVERE, tl("connectionFailed"), ex); } } diff --git a/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsConnect.java b/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsConnect.java index 42bb5a0b4f8..77af0c1469d 100644 --- a/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsConnect.java +++ b/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsConnect.java @@ -5,18 +5,16 @@ import org.bukkit.plugin.Plugin; import java.util.logging.Level; -import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; class EssentialsConnect { - private static final Logger logger = Logger.getLogger("EssentialsProtect"); private final IEssentials ess; private final IProtect protect; EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) { if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) { - logger.log(Level.WARNING, tl("versionMismatchAll")); + essProtect.getLogger().log(Level.WARNING, tl("versionMismatchAll")); } ess = (IEssentials) essPlugin; protect = (IProtect) essProtect; diff --git a/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsProtect.java index ff673dde2e3..d3496c19b1a 100644 --- a/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsProtect.java +++ b/EssentialsProtect/src/main/java/com/earth2me/essentials/protect/EssentialsProtect.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.protect; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.metrics.MetricsWrapper; import com.earth2me.essentials.utils.VersionUtil; import org.bukkit.Material; @@ -13,6 +14,7 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; +import java.util.logging.Logger; public class EssentialsProtect extends JavaPlugin implements IProtect { private final Map settingsBoolean = new EnumMap<>(ProtectConfig.class); @@ -38,6 +40,16 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + private void initialize(final PluginManager pm, final Plugin essPlugin) { getLogger().log(Level.INFO, "Continuing to enable Protect."); ess = new EssentialsConnect(essPlugin, this); diff --git a/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawn.java b/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawn.java index a23a28b1bcc..fd2a2b42134 100644 --- a/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawn.java +++ b/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawn.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.spawn; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IEssentials; import org.bukkit.Location; @@ -12,6 +13,7 @@ import org.bukkit.plugin.java.JavaPlugin; import java.util.logging.Level; +import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; @@ -54,6 +56,25 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + + public static Logger getWrappedLogger() { + try { + return EssentialsLogger.getLoggerProvider("EssentialsSpawn"); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return Logger.getLogger("EssentialsSpawn"); + } + } + @Override public void onDisable() { } diff --git a/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java b/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java index e72522a856e..59d8b4efeed 100644 --- a/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java +++ b/EssentialsSpawn/src/main/java/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java @@ -24,7 +24,7 @@ import static com.earth2me.essentials.I18n.tl; class EssentialsSpawnPlayerListener implements Listener { - private static final Logger logger = Logger.getLogger("EssentialsSpawn"); + private static final Logger logger = EssentialsSpawn.getWrappedLogger(); private final transient IEssentials ess; private final transient SpawnStorage spawns; diff --git a/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/EssentialsXMPP.java b/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/EssentialsXMPP.java index 5ddc91c014c..dee2e2673a5 100644 --- a/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/EssentialsXMPP.java +++ b/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/EssentialsXMPP.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.xmpp; +import com.earth2me.essentials.EssentialsLogger; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IUser; @@ -13,6 +14,7 @@ import java.util.List; import java.util.Locale; import java.util.logging.Level; +import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; @@ -60,6 +62,25 @@ public void onEnable() { } } + @Override + public Logger getLogger() { + try { + return EssentialsLogger.getLoggerProvider(this); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return super.getLogger(); + } + } + + public static Logger getWrappedLogger() { + try { + return EssentialsLogger.getLoggerProvider("EssentialsXMPP"); + } catch (Throwable ignored) { + // In case Essentials isn't installed/loaded + return Logger.getLogger("EssentialsXMPP"); + } + } + @Override public void onDisable() { if (xmpp != null) { diff --git a/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/XMPPManager.java b/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/XMPPManager.java index d8dc4c03515..c1e59e04e4f 100644 --- a/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/XMPPManager.java +++ b/EssentialsXMPP/src/main/java/com/earth2me/essentials/xmpp/XMPPManager.java @@ -35,7 +35,7 @@ import static com.earth2me.essentials.I18n.tl; public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf { - private static final Logger logger = Logger.getLogger("EssentialsXMPP"); + private static final Logger logger = EssentialsXMPP.getWrappedLogger(); private static final SimpleFormatter formatter = new SimpleFormatter(); private final transient EssentialsConfiguration config; private final transient Map chats = Collections.synchronizedMap(new HashMap<>()); diff --git a/providers/BaseProviders/src/main/java/net/ess3/provider/LoggerProvider.java b/providers/BaseProviders/src/main/java/net/ess3/provider/LoggerProvider.java new file mode 100644 index 00000000000..aaba0c8b822 --- /dev/null +++ b/providers/BaseProviders/src/main/java/net/ess3/provider/LoggerProvider.java @@ -0,0 +1,39 @@ +package net.ess3.provider; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class LoggerProvider extends Logger { + public LoggerProvider(final String name) { + super(name, null); + } + + protected abstract void doTheLog(Level level, String message, Throwable throwable); + + protected abstract void doTheLog(Level level, String message); + + @Override + public void log(Level level, String msg) { + doTheLog(level, msg); + } + + @Override + public void log(Level level, String msg, Throwable thrown) { + doTheLog(level, msg, thrown); + } + + @Override + public void warning(String message) { + doTheLog(Level.WARNING, message); + } + + @Override + public void info(String message) { + doTheLog(Level.INFO, message); + } + + @Override + public void severe(String message) { + doTheLog(Level.SEVERE, message); + } +} diff --git a/providers/BaseProviders/src/main/java/net/ess3/provider/providers/BaseLoggerProvider.java b/providers/BaseProviders/src/main/java/net/ess3/provider/providers/BaseLoggerProvider.java new file mode 100644 index 00000000000..e65a3eba331 --- /dev/null +++ b/providers/BaseProviders/src/main/java/net/ess3/provider/providers/BaseLoggerProvider.java @@ -0,0 +1,25 @@ +package net.ess3.provider.providers; + +import net.ess3.provider.LoggerProvider; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class BaseLoggerProvider extends LoggerProvider { + private final Logger logger; + + public BaseLoggerProvider(final Logger logger) { + super(logger.getName()); + this.logger = logger; + } + + @Override + protected void doTheLog(Level level, String message, Throwable throwable) { + logger.log(level, message, throwable); + } + + @Override + protected void doTheLog(Level level, String message) { + logger.log(level, message); + } +} diff --git a/providers/PaperProvider/build.gradle b/providers/PaperProvider/build.gradle index 729cc7b7ca8..1a4c356d3a3 100644 --- a/providers/PaperProvider/build.gradle +++ b/providers/PaperProvider/build.gradle @@ -10,8 +10,8 @@ dependencies { implementation(project(':providers:BaseProviders')) { exclude(module: 'spigot-api') } - compileOnly 'io.papermc.paper:paper-api:1.18.1-R0.1-SNAPSHOT' - compileOnly 'io.papermc.paper:paper-mojangapi:1.18.1-R0.1-SNAPSHOT' + compileOnly 'io.papermc.paper:paper-api:1.18.2-R0.1-SNAPSHOT' + compileOnly 'io.papermc.paper:paper-mojangapi:1.18.2-R0.1-SNAPSHOT' } essentials { diff --git a/providers/PaperProvider/src/main/java/net/ess3/provider/providers/PaperLoggerProvider.java b/providers/PaperProvider/src/main/java/net/ess3/provider/providers/PaperLoggerProvider.java new file mode 100644 index 00000000000..6fd7b31d123 --- /dev/null +++ b/providers/PaperProvider/src/main/java/net/ess3/provider/providers/PaperLoggerProvider.java @@ -0,0 +1,50 @@ +package net.ess3.provider.providers; + +import net.ess3.provider.LoggerProvider; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.plugin.Plugin; + +import java.util.logging.Level; + +public class PaperLoggerProvider extends LoggerProvider { + private final ComponentLogger logger; + + public PaperLoggerProvider(final Plugin plugin) { + super(plugin.getComponentLogger().getName()); + this.logger = plugin.getComponentLogger(); + } + + @Override + protected void doTheLog(Level level, String message, Throwable throwable) { + final Component component = LegacyComponentSerializer.legacySection().deserialize(message); + if (level == Level.SEVERE) { + logger.error(component, throwable); + } else if (level == Level.WARNING) { + logger.warn(component, throwable); + } else if (level == Level.INFO) { + logger.info(component, throwable); + } else if (level == Level.FINE) { + logger.trace(component, throwable); + } else { + throw new IllegalArgumentException("Unknown level: " + level); + } + } + + @Override + protected void doTheLog(Level level, String message) { + final Component component = LegacyComponentSerializer.legacySection().deserialize(message); + if (level == Level.SEVERE) { + logger.error(component); + } else if (level == Level.WARNING) { + logger.warn(component); + } else if (level == Level.INFO) { + logger.info(component); + } else if (level == Level.FINE) { + logger.trace(component); + } else { + throw new IllegalArgumentException("Unknown level: " + level); + } + } +}