diff --git a/src/main/java/com/sk89q/worldguard/blacklist/Blacklist.java b/src/main/java/com/sk89q/worldguard/blacklist/Blacklist.java index 42823372..5c1138e6 100644 --- a/src/main/java/com/sk89q/worldguard/blacklist/Blacklist.java +++ b/src/main/java/com/sk89q/worldguard/blacklist/Blacklist.java @@ -39,16 +39,16 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; - -import static com.google.common.base.Preconditions.checkNotNull; +import java.util.logging.Logger; public abstract class Blacklist { + private static final Logger log = Logger.getLogger(Blacklist.class.getCanonicalName()); + private MatcherIndex index = MatcherIndex.getEmptyInstance(); private final BlacklistLoggerHandler blacklistLogger = new BlacklistLoggerHandler(); private BlacklistEvent lastEvent; private boolean useAsWhitelist; - private final java.util.logging.Logger logger; private Cache repeatingEventCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterAccess(30, TimeUnit.SECONDS) @@ -59,10 +59,8 @@ public TrackedEvent load(String s) throws Exception { } }); - public Blacklist(boolean useAsWhitelist, java.util.logging.Logger logger) { - checkNotNull(logger); + public Blacklist(boolean useAsWhitelist) { this.useAsWhitelist = useAsWhitelist; - this.logger = logger; } /** @@ -93,7 +91,7 @@ public boolean isWhitelist() { } /** - * Get the logger. + * Get the log. * * @return The logger used in this blacklist */ @@ -165,14 +163,14 @@ public void load(File file) throws IOException { builder.add(matcher, entry); currentEntries.add(entry); } catch (TargetMatcherParseException e) { - logger.log(Level.WARNING, "Could not parse a block/item heading: " + e.getMessage()); + log.log(Level.WARNING, "Could not parse a block/item heading: " + e.getMessage()); } } } else if (currentEntries != null) { String[] parts = line.split("="); if (parts.length == 1) { - logger.log(Level.WARNING, "Found option with no value " + file.getName() + " for '" + line + "'"); + log.log(Level.WARNING, "Found option with no value " + file.getName() + " for '" + line + "'"); continue; } @@ -209,10 +207,10 @@ public void load(File file) throws IOException { } if (unknownOption) { - logger.log(Level.WARNING, "Unknown option '" + parts[0] + "' in " + file.getName() + " for '" + line + "'"); + log.log(Level.WARNING, "Unknown option '" + parts[0] + "' in " + file.getName() + " for '" + line + "'"); } } else { - logger.log(Level.WARNING, "Found option with no heading " + log.log(Level.WARNING, "Found option with no heading " + file.getName() + " for '" + line + "'"); } } @@ -246,7 +244,7 @@ private List parseActions(BlacklistEntry entry, String raw) { } if (!found) { - logger.log(Level.WARNING, "Unknown blacklist action: " + name); + log.log(Level.WARNING, "Unknown blacklist action: " + name); } } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/BukkitBlacklist.java b/src/main/java/com/sk89q/worldguard/bukkit/BukkitBlacklist.java index d333a650..13639239 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/BukkitBlacklist.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/BukkitBlacklist.java @@ -21,12 +21,14 @@ import com.sk89q.worldguard.blacklist.Blacklist; +import java.util.logging.Logger; + class BukkitBlacklist extends Blacklist { private WorldGuardPlugin plugin; public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) { - super(useAsWhitelist, plugin.getLogger()); + super(useAsWhitelist); this.plugin = plugin; } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/ConfigurationManager.java b/src/main/java/com/sk89q/worldguard/bukkit/ConfigurationManager.java index da655925..57c71599 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/ConfigurationManager.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/ConfigurationManager.java @@ -41,6 +41,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.logging.Logger; /** * Represents the global configuration and also delegates configuration @@ -51,6 +52,8 @@ */ public class ConfigurationManager { + private static final Logger log = Logger.getLogger(ConfigurationManager.class.getCanonicalName()); + private static final String CONFIG_HEADER = "#\r\n" + "# WorldGuard's main configuration file\r\n" + "#\r\n" + @@ -141,7 +144,7 @@ public void load() { try { config.load(); } catch (IOException e) { - plugin.getLogger().severe("Error reading configuration for global config: "); + log.severe("Error reading configuration for global config: "); e.printStackTrace(); } @@ -208,7 +211,7 @@ public void unload() { public void disableUuidMigration() { config.setProperty("regions.uuid-migration.perform-on-next-start", false); if (!config.save()) { - plugin.getLogger().severe("Error saving configuration!"); + log.severe("Error saving configuration!"); } } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/WorldConfiguration.java b/src/main/java/com/sk89q/worldguard/bukkit/WorldConfiguration.java index 903ae86b..7dae6009 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/WorldConfiguration.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/WorldConfiguration.java @@ -43,6 +43,7 @@ import java.util.Map; import java.util.Set; import java.util.logging.Level; +import java.util.logging.Logger; /** * Holds the configuration for individual worlds. @@ -52,6 +53,8 @@ */ public class WorldConfiguration { + private static final Logger log = Logger.getLogger(WorldConfiguration.class.getCanonicalName()); + public static final String CONFIG_HEADER = "#\r\n" + "# WorldGuard's world configuration file\r\n" + "#\r\n" + @@ -197,7 +200,7 @@ public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcess loadConfiguration(); if (summaryOnStart) { - plugin.getLogger().info("Loaded configuration for world '" + worldName + "'"); + log.info("Loaded configuration for world '" + worldName + "'"); } } @@ -300,7 +303,7 @@ private void loadConfiguration() { try { config.load(); } catch (IOException e) { - plugin.getLogger().severe("Error reading configuration for world " + worldName + ": "); + log.severe("Error reading configuration for world " + worldName + ": "); e.printStackTrace(); } @@ -317,7 +320,7 @@ private void loadConfiguration() { PotionEffectType effect = PotionEffectType.getByName(potionName); if (effect == null) { - plugin.getLogger().warning("Unknown potion effect type '" + potionName + "'"); + log.warning("Unknown potion effect type '" + potionName + "'"); } else { blockPotions.add(effect); } @@ -438,9 +441,9 @@ private void loadConfiguration() { EntityType creature = EntityType.fromName(creatureName); if (creature == null) { - plugin.getLogger().warning("Unknown mob type '" + creatureName + "'"); + log.warning("Unknown mob type '" + creatureName + "'"); } else if (!creature.isAlive()) { - plugin.getLogger().warning("Entity type '" + creatureName + "' is not a creature"); + log.warning("Entity type '" + creatureName + "' is not a creature"); } else { blockCreatureSpawn.add(creature); } @@ -481,53 +484,53 @@ private void loadConfiguration() { } else { this.blacklist = blist; if (summaryOnStart) { - plugin.getLogger().log(Level.INFO, "Blacklist loaded."); + log.log(Level.INFO, "Blacklist loaded."); } BlacklistLoggerHandler blacklistLogger = blist.getLogger(); if (logDatabase) { - blacklistLogger.addHandler(new DatabaseHandler(dsn, user, pass, table, worldName, plugin.getLogger())); + blacklistLogger.addHandler(new DatabaseHandler(dsn, user, pass, table, worldName, log)); } if (logConsole) { - blacklistLogger.addHandler(new ConsoleHandler(worldName, plugin.getLogger())); + blacklistLogger.addHandler(new ConsoleHandler(worldName, log)); } if (logFile) { FileHandler handler = - new FileHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger()); + new FileHandler(logFilePattern, logFileCacheSize, worldName, log); blacklistLogger.addHandler(handler); } } } catch (FileNotFoundException e) { - plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist."); + log.log(Level.WARNING, "WorldGuard blacklist does not exist."); } catch (IOException e) { - plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: " + log.log(Level.WARNING, "Could not load WorldGuard blacklist: " + e.getMessage()); } // Print an overview of settings if (summaryOnStart) { - plugin.getLogger().log(Level.INFO, blockTNTExplosions + log.log(Level.INFO, blockTNTExplosions ? "(" + worldName + ") TNT ignition is blocked." : "(" + worldName + ") TNT ignition is PERMITTED."); - plugin.getLogger().log(Level.INFO, blockLighter + log.log(Level.INFO, blockLighter ? "(" + worldName + ") Lighters are blocked." : "(" + worldName + ") Lighters are PERMITTED."); - plugin.getLogger().log(Level.INFO, preventLavaFire + log.log(Level.INFO, preventLavaFire ? "(" + worldName + ") Lava fire is blocked." : "(" + worldName + ") Lava fire is PERMITTED."); if (disableFireSpread) { - plugin.getLogger().log(Level.INFO, "(" + worldName + ") All fire spread is disabled."); + log.log(Level.INFO, "(" + worldName + ") All fire spread is disabled."); } else { if (disableFireSpreadBlocks.size() > 0) { - plugin.getLogger().log(Level.INFO, "(" + worldName + log.log(Level.INFO, "(" + worldName + ") Fire spread is limited to " + disableFireSpreadBlocks.size() + " block types."); } else { - plugin.getLogger().log(Level.INFO, "(" + worldName + log.log(Level.INFO, "(" + worldName + ") Fire spread is UNRESTRICTED."); } } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java b/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java index 21f205db..6994ca6f 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java @@ -66,6 +66,7 @@ import com.sk89q.worldguard.protection.util.UnresolvedNamesException; import com.sk89q.worldguard.util.FatalConfigurationLoadingException; import com.sk89q.worldguard.util.concurrent.EvenMoreExecutors; +import com.sk89q.worldguard.util.logging.RecordMessagePrefixer; import com.sk89q.worldguard.util.task.SimpleSupervisor; import com.sk89q.worldguard.util.task.Supervisor; import com.sk89q.worldguard.util.task.Task; @@ -99,6 +100,7 @@ import java.util.concurrent.TimeUnit; import java.util.jar.JarFile; import java.util.logging.Level; +import java.util.logging.Logger; import java.util.zip.ZipEntry; /** @@ -106,6 +108,8 @@ */ public class WorldGuardPlugin extends JavaPlugin { + private static final Logger log = Logger.getLogger(WorldGuardPlugin.class.getCanonicalName()); + private static WorldGuardPlugin inst; private final CommandsManager commands; private final ConfigurationManager configuration = new ConfigurationManager(this); @@ -145,6 +149,8 @@ public static WorldGuardPlugin inst() { @Override @SuppressWarnings("deprecation") public void onEnable() { + configureLogger(); + getDataFolder().mkdirs(); // Need to create the plugins/WorldGuard folder executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20)); @@ -171,7 +177,7 @@ public void run() { try { profileCache = new SQLiteCache(new File(cacheDir, "profiles.sqlite")); } catch (IOException e) { - getLogger().log(Level.WARNING, "Failed to initialize SQLite profile cache"); + log.log(Level.WARNING, "Failed to initialize SQLite profile cache"); profileCache = new HashMapCache(); } @@ -187,9 +193,9 @@ public void run() { // Load the configuration configuration.load(); } catch (FatalConfigurationLoadingException e) { - getLogger().log(Level.WARNING, "Encountered fatal error while loading configuration", e); + log.log(Level.WARNING, "Encountered fatal error while loading configuration", e); getServer().shutdown(); - getLogger().log(Level.WARNING, "\n" + + log.log(Level.WARNING, "\n" + "******************************************************\n" + "* Failed to load WorldGuard configuration!\n" + "* \n" + @@ -201,7 +207,7 @@ public void run() { "******************************************************\n"); } - getLogger().info("Loading region data..."); + log.info("Loading region data..."); regionContainer.initialize(); flagStateManager = new FlagStateManager(this); @@ -228,7 +234,7 @@ public void run() { (new BlockedPotionsListener(this)).registerEvents(); (new EventAbstractionListener(this)).registerEvents(); if ("true".equalsIgnoreCase(System.getProperty("worldguard.debug.listener"))) { - (new DebuggingListener(this, getLogger())).registerEvents(); + (new DebuggingListener(this, log)).registerEvents(); } configuration.updateCommandBookGodMode(); @@ -260,7 +266,7 @@ public void onDisable() { executorService.shutdown(); try { - getLogger().log(Level.INFO, "Shutting down executor and waiting for any pending tasks..."); + log.log(Level.INFO, "Shutting down executor and waiting for any pending tasks..."); List> tasks = supervisor.getTasks(); if (!tasks.isEmpty()) { @@ -269,7 +275,7 @@ public void onDisable() { builder.append("\n"); builder.append(task.getName()); } - getLogger().log(Level.INFO, builder.toString()); + log.log(Level.INFO, builder.toString()); } Futures.successfulAsList(tasks).get(); @@ -277,7 +283,7 @@ public void onDisable() { } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { - getLogger().log(Level.WARNING, "Some tasks failed while waiting for remaining tasks to finish", e); + log.log(Level.WARNING, "Some tasks failed while waiting for remaining tasks to finish", e); } regionContainer.unload(); @@ -325,7 +331,7 @@ public String convertThrowable(@Nullable Throwable throwable) { } else if (throwable instanceof CommandException) { return throwable.getMessage(); } else { - getLogger().log(Level.WARNING, "WorldGuard encountered an unexpected error", throwable); + log.log(Level.WARNING, "WorldGuard encountered an unexpected error", throwable); return "WorldGuard: An unexpected error occurred! Please see the server console."; } } @@ -841,6 +847,13 @@ public LocalPlayer wrapPlayer(Player player) { return new BukkitPlayer(this, player); } + /** + * Configure WorldGuard's loggers. + */ + private void configureLogger() { + RecordMessagePrefixer.register(Logger.getLogger("com.sk89q.worldguard"), "[WorldGuard] "); + } + /** * Create a default configuration file from the .jar. * @@ -868,7 +881,7 @@ public void createDefaultConfiguration(File actual, if (copy == null) throw new FileNotFoundException(); input = file.getInputStream(copy); } catch (IOException e) { - getLogger().severe("Unable to read default configuration: " + defaultName); + log.severe("Unable to read default configuration: " + defaultName); } if (input != null) { @@ -882,7 +895,7 @@ public void createDefaultConfiguration(File actual, output.write(buf, 0, length); } - getLogger().info("Default configuration file written: " + log.info("Default configuration file written: " + actual.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); @@ -920,7 +933,7 @@ public void broadcastNotification(String msg) { player.sendMessage(msg); } } - getLogger().info(msg); + log.info(msg); } /** @@ -1004,4 +1017,5 @@ public String replaceMacros(CommandSender sender, String message) { return message; } + } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java b/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java index 44325133..3477279b 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java @@ -71,7 +71,7 @@ public void reload(CommandContext args, CommandSender sender) throws CommandExce if (sender instanceof Player) { handler = new LoggerToChatHandler(sender); handler.setLevel(Level.ALL); - minecraftLogger = Logger.getLogger("Minecraft"); + minecraftLogger = Logger.getLogger("com.sk89q.worldguard"); minecraftLogger.addHandler(handler); } diff --git a/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommands.java b/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommands.java index f5173421..82a87798 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommands.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommands.java @@ -77,6 +77,7 @@ */ public final class RegionCommands extends RegionCommandsBase { + private static final Logger log = Logger.getLogger(RegionCommands.class.getCanonicalName()); private final WorldGuardPlugin plugin; public RegionCommands(WorldGuardPlugin plugin) { @@ -874,7 +875,7 @@ public void migrateDB(CommandContext args, CommandSender sender) throws CommandE "the target driver, then WorldGuard is now using the new data. If not, you have to adjust your " + "configuration to use the new driver and then restart your server."); } catch (MigrationException e) { - plugin.getLogger().log(Level.WARNING, "Failed to migrate", e); + log.log(Level.WARNING, "Failed to migrate", e); throw new CommandException("Error encountered while migrating: " + e.getMessage()); } finally { if (minecraftLogger != null) { @@ -918,7 +919,7 @@ public void migrateUuid(CommandContext args, CommandSender sender) throws Comman container.migrate(migration); sender.sendMessage(ChatColor.YELLOW + "Migration complete!"); } catch (MigrationException e) { - plugin.getLogger().log(Level.WARNING, "Failed to migrate", e); + log.log(Level.WARNING, "Failed to migrate", e); throw new CommandException("Error encountered while migrating: " + e.getMessage()); } finally { if (minecraftLogger != null) { diff --git a/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardPlayerListener.java b/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardPlayerListener.java index 60749231..51bea8fd 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardPlayerListener.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardPlayerListener.java @@ -62,6 +62,7 @@ import java.util.Iterator; import java.util.Set; import java.util.logging.Level; +import java.util.logging.Logger; import java.util.regex.Pattern; /** @@ -69,6 +70,7 @@ */ public class WorldGuardPlayerListener implements Listener { + private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName()); private Pattern opPattern = Pattern.compile("^/op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE); private WorldGuardPlugin plugin; @@ -329,7 +331,7 @@ public void onPlayerJoin(PlayerJoinEvent event) { } if (removed > 10) { - plugin.getLogger().info("Halt-Act: " + removed + " entities (>10) auto-removed from " + log.info("Halt-Act: " + removed + " entities (>10) auto-removed from " + player.getWorld().toString()); } } @@ -341,12 +343,12 @@ public void onPlayerJoin(PlayerJoinEvent event) { if (!cfg.hasCommandBookGodMode() && cfg.autoGodMode && (plugin.inGroup(player, "wg-invincible") || plugin.hasPermission(player, "worldguard.auto-invincible"))) { - plugin.getLogger().log(Level.INFO, "Enabled auto-god mode for " + player.getName()); + log.log(Level.INFO, "Enabled auto-god mode for " + player.getName()); cfg.enableGodMode(player); } if (plugin.inGroup(player, "wg-amphibious")) { - plugin.getLogger().log(Level.INFO, "Enabled no-drowning mode for " + player.getName() + " (player is in group 'wg-amphibious')"); + log.log(Level.INFO, "Enabled no-drowning mode for " + player.getName() + " (player is in group 'wg-amphibious')"); cfg.enableAmphibiousMode(player); } @@ -398,7 +400,7 @@ public void onPlayerLogin(PlayerLoginEvent event) { if (!hostname.equals(hostKey)) { event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "You did not join with the valid host key!"); - plugin.getLogger().warning("WorldGuard host key check: " + + log.warning("WorldGuard host key check: " + player.getName() + " joined with '" + hostname + "' but '" + hostKey + "' was expected. Kicked!"); return; diff --git a/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardWorldListener.java b/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardWorldListener.java index 89a498c7..cb5cb58f 100644 --- a/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardWorldListener.java +++ b/src/main/java/com/sk89q/worldguard/bukkit/listener/WorldGuardWorldListener.java @@ -30,8 +30,11 @@ import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.WorldLoadEvent; +import java.util.logging.Logger; + public class WorldGuardWorldListener implements Listener { + private static final Logger log = Logger.getLogger(WorldGuardWorldListener.class.getCanonicalName()); private WorldGuardPlugin plugin; /** @@ -65,8 +68,7 @@ public void onChunkLoad(ChunkLoadEvent event) { } if (removed > 50) { - plugin.getLogger().info("Halt-Act: " + removed + " entities (>50) auto-removed from " - + event.getChunk().toString()); + log.info("Halt-Act: " + removed + " entities (>50) auto-removed from " + event.getChunk().toString()); } } } diff --git a/src/main/java/com/sk89q/worldguard/util/logging/RecordMessagePrefixer.java b/src/main/java/com/sk89q/worldguard/util/logging/RecordMessagePrefixer.java new file mode 100644 index 00000000..86278aac --- /dev/null +++ b/src/main/java/com/sk89q/worldguard/util/logging/RecordMessagePrefixer.java @@ -0,0 +1,74 @@ +/* + * WorldGuard, a suite of tools for Minecraft + * Copyright (C) sk89q + * Copyright (C) WorldGuard team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldguard.util.logging; + +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class RecordMessagePrefixer extends Handler { + + private final Logger parentLogger; + private final String prefix; + + public RecordMessagePrefixer(Logger parentLogger, String prefix) { + checkNotNull(parentLogger); + checkNotNull(prefix); + + this.parentLogger = parentLogger; + this.prefix = prefix; + } + + @Override + public void publish(LogRecord record) { + // Ideally we would make a copy of the record + record.setMessage(prefix + record.getMessage()); + parentLogger.log(record); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + + /** + * Register a prefix handler on the given logger. + * + * @param logger the logger + * @param prefix the prefix + */ + public static void register(Logger logger, String prefix) { + checkNotNull(logger); + + logger.setUseParentHandlers(false); + for (Handler handler : logger.getHandlers()) { + if (handler instanceof RecordMessagePrefixer) { + logger.removeHandler(handler); + } + } + logger.addHandler(new RecordMessagePrefixer(logger.getParent(), prefix)); + } + +}