[BLEEDING] Use the new logging framework from now on (read details).

* All logging is also going into the log file (always), debug output is
mostly/only going into the log file. File logging uses an asynchronously
processed queue now (!).
* Specify an existing directory (e.g. logs) and log files will named
after date + sequence number, changing with every reloading of the
configuration.
* Console and ingame logging remain within the primary thread.
* No extra configurability for customization, yet.
* Not all places have been cleaned up, concerning log levels. target
streams and package naming.
* Work in progress.
This commit is contained in:
asofold 2014-11-19 00:00:31 +01:00
parent 2f4d689722
commit ec36e879d3
20 changed files with 170 additions and 235 deletions

View File

@ -1,117 +0,0 @@
package fr.neatmonster.nocheatplus.logging;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import fr.neatmonster.nocheatplus.utilities.StringUtil;
/**
* Could not think of anything better, likely a refactoring stage.
* @author mc_dev
*
*/
public class StaticLogFile {
/**
* The formatter that is used to format the log file.
*/
protected static class LogFileFormatter extends Formatter {
/**
* Create a new instance of the log file formatter.
*
* @return the log file formatter
*/
public static LogFileFormatter newInstance() {
return new LogFileFormatter();
}
/** The date formatter. */
private final SimpleDateFormat date;
/**
* Instantiates a new log file formatter.
*/
private LogFileFormatter() {
date = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
}
/* (non-Javadoc)
* @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
*/
@Override
public String format(final LogRecord record) {
final StringBuilder builder = new StringBuilder();
final Throwable ex = record.getThrown();
builder.append(date.format(record.getMillis()));
builder.append(" [");
builder.append(record.getLevel().getLocalizedName().toUpperCase());
builder.append("] ");
builder.append(record.getMessage());
builder.append('\n');
if (ex != null) {
builder.append(StringUtil.throwableToString(ex));
}
return builder.toString();
}
}
/** The file logger. */
public static Logger fileLogger = null;
/** The file handler. */
private static FileHandler fileHandler = null;
/**
* Cleanup.
*/
public static void cleanup() {
fileHandler.flush();
fileHandler.close();
final Logger logger = Logger.getLogger("NoCheatPlus");
logger.removeHandler(fileHandler);
fileHandler = null;
}
/**
* @throws RuntimeException wrapping actual exceptions (crate directories, file handlers).
* @param logFile
*/
public static void setupLogger(File logFile){
// Setup the file logger.
final Logger logger = Logger.getAnonymousLogger();
logger.setLevel(Level.INFO);
logger.setUseParentHandlers(false);
for (final Handler h : logger.getHandlers()) {
logger.removeHandler(h);
}
if (fileHandler != null) {
fileHandler.close();
logger.removeHandler(fileHandler);
fileHandler = null;
}
try {
try {
logFile.getParentFile().mkdirs();
} catch (final Exception e) {
throw new RuntimeException(e); // TODO
}
fileHandler = new FileHandler(logFile.getCanonicalPath(), true);
fileHandler.setLevel(Level.ALL);
fileHandler.setFormatter(StaticLogFile.LogFileFormatter.newInstance());
logger.addHandler(fileHandler);
} catch (final Exception e) {
throw new RuntimeException(e); // TODO
}
fileLogger = logger;
}
}

View File

@ -8,8 +8,8 @@ import fr.neatmonster.nocheatplus.actions.ActionList;
import fr.neatmonster.nocheatplus.checks.ViolationData; import fr.neatmonster.nocheatplus.checks.ViolationData;
import fr.neatmonster.nocheatplus.config.ConfPaths; import fr.neatmonster.nocheatplus.config.ConfPaths;
import fr.neatmonster.nocheatplus.config.ConfigFileWithActions; import fr.neatmonster.nocheatplus.config.ConfigFileWithActions;
import fr.neatmonster.nocheatplus.logging.StaticLog; import fr.neatmonster.nocheatplus.logging.LogManager;
import fr.neatmonster.nocheatplus.logging.StaticLogFile; import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.utilities.ColorUtil; import fr.neatmonster.nocheatplus.utilities.ColorUtil;
/** /**
@ -99,14 +99,15 @@ public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
public boolean execute(final ViolationData violationData) { public boolean execute(final ViolationData violationData) {
if (!violationData.player.hasPermission(violationData.getPermissionSilent())) { if (!violationData.player.hasPermission(violationData.getPermissionSilent())) {
final String message = super.getMessage(violationData); final String message = super.getMessage(violationData);
final LogManager logManager = NCPAPIProvider.getNoCheatPlusAPI().getLogManager();
if (toChat) { if (toChat) {
NCPAPIProvider.getNoCheatPlusAPI().sendAdminNotifyMessage(ColorUtil.replaceColors(prefixChat + message)); logManager.info(Streams.NOTIFY_INGAME, ColorUtil.replaceColors(prefixChat + message));
} }
if (toConsole) { if (toConsole) {
StaticLog.logInfo(ColorUtil.removeColors(prefixConsole + message)); logManager.info(Streams.SERVER_LOGGER, ColorUtil.removeColors(prefixConsole + message));
} }
if (toFile) { if (toFile) {
StaticLogFile.fileLogger.info(ColorUtil.removeColors(prefixFile + message)); logManager.info(Streams.DEFAULT_FILE, ColorUtil.removeColors(prefixFile + message));
} }
} }
return false; return false;

View File

@ -172,7 +172,7 @@ public class BlockBreakListener extends CheckListener {
priority = EventPriority.MONITOR) priority = EventPriority.MONITOR)
public void onPlayerAnimation(final PlayerAnimationEvent event) { public void onPlayerAnimation(final PlayerAnimationEvent event) {
// Just set a flag to true when the arm was swung. // Just set a flag to true when the arm was swung.
// System.out.println("Animation"); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "Animation");
BlockBreakData.getData(event.getPlayer()).noSwingArmSwung = true; BlockBreakData.getData(event.getPlayer()).noSwingArmSwung = true;
} }
@ -186,7 +186,7 @@ public class BlockBreakListener extends CheckListener {
@EventHandler( @EventHandler(
ignoreCancelled = false, priority = EventPriority.LOWEST) ignoreCancelled = false, priority = EventPriority.LOWEST)
public void onPlayerInteract(final PlayerInteractEvent event) { public void onPlayerInteract(final PlayerInteractEvent event) {
// System.out.println("Interact("+event.isCancelled()+"): " + event.getClickedBlock()); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "Interact("+event.isCancelled()+"): " + event.getClickedBlock());
// The following is to set the "first damage time" for a block. // The following is to set the "first damage time" for a block.
// Return if it is not left clicking a block. // Return if it is not left clicking a block.

View File

@ -36,6 +36,7 @@ import fr.neatmonster.nocheatplus.checks.moving.MovingData;
import fr.neatmonster.nocheatplus.checks.moving.MovingListener; import fr.neatmonster.nocheatplus.checks.moving.MovingListener;
import fr.neatmonster.nocheatplus.compat.BridgeHealth; import fr.neatmonster.nocheatplus.compat.BridgeHealth;
import fr.neatmonster.nocheatplus.components.JoinLeaveListener; import fr.neatmonster.nocheatplus.components.JoinLeaveListener;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.permissions.Permissions; import fr.neatmonster.nocheatplus.permissions.Permissions;
import fr.neatmonster.nocheatplus.stats.Counters; import fr.neatmonster.nocheatplus.stats.Counters;
import fr.neatmonster.nocheatplus.utilities.TickTask; import fr.neatmonster.nocheatplus.utilities.TickTask;
@ -321,7 +322,7 @@ public class FightListener extends CheckListener implements JoinLeaveListener{
// Angle check. // Angle check.
if (angle.check(player, worldChanged, data, cc)) { if (angle.check(player, worldChanged, data, cc)) {
if (!cancelled && cc.debug) { if (!cancelled && cc.debug) {
System.out.println(player.getName() + " fight.angle cancel without yawrate cancel."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " fight.angle cancel without yawrate cancel.");
} }
cancelled = true; cancelled = true;
} }
@ -353,7 +354,7 @@ public class FightListener extends CheckListener implements JoinLeaveListener{
// TODO: What would mData.lostSprintCount > 0 mean here? // TODO: What would mData.lostSprintCount > 0 mean here?
mData.lostSprintCount = 7; mData.lostSprintCount = 7;
if ((cc.debug || mc.debug) && BuildParameters.debugLevel > 0){ if ((cc.debug || mc.debug) && BuildParameters.debugLevel > 0){
System.out.println(player.getName() + " (lostsprint) hDist to last from: " + hDist + " | targetdist=" + TrigUtil.distance(loc.getX(), loc.getZ(), damagedLoc.getX(), damagedLoc.getZ()) + " | sprinting=" + player.isSprinting() + " | food=" + player.getFoodLevel() +" | hbuf=" + mData.sfHorizontalBuffer); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " (lostsprint) hDist to last from: " + hDist + " | targetdist=" + TrigUtil.distance(loc.getX(), loc.getZ(), damagedLoc.getX(), damagedLoc.getZ()) + " | sprinting=" + player.isSprinting() + " | food=" + player.getFoodLevel() +" | hbuf=" + mData.sfHorizontalBuffer);
} }
} }
} }
@ -365,7 +366,7 @@ public class FightListener extends CheckListener implements JoinLeaveListener{
if (!cancelled && data.attackPenalty.isPenalty(now)) { if (!cancelled && data.attackPenalty.isPenalty(now)) {
cancelled = true; cancelled = true;
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " ~ attack penalty."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " ~ attack penalty.");
} }
} }
@ -421,7 +422,7 @@ public class FightListener extends CheckListener implements JoinLeaveListener{
damagedData.fastHealRefTime = System.currentTimeMillis(); damagedData.fastHealRefTime = System.currentTimeMillis();
} }
} }
// System.out.println(event.getCause()); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, event.getCause());
// Attacking entities. // Attacking entities.
if (event instanceof EntityDamageByEntityEvent) { if (event instanceof EntityDamageByEntityEvent) {
final EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; final EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event;

View File

@ -80,7 +80,7 @@ public class AxisVelocity {
// TODO: Could check for alternating signum (error). // TODO: Could check for alternating signum (error).
final Velocity vel = it.next(); final Velocity vel = it.next();
if (vel.actCount <= 0 || vel.tick < tick) { if (vel.actCount <= 0 || vel.tick < tick) {
// System.out.println("Invalidate queued: " + vel); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "Invalidate queued: " + vel);
it.remove(); it.remove();
} }
} }

View File

@ -63,6 +63,7 @@ import fr.neatmonster.nocheatplus.config.ConfigManager;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
import fr.neatmonster.nocheatplus.logging.DebugUtil; import fr.neatmonster.nocheatplus.logging.DebugUtil;
import fr.neatmonster.nocheatplus.logging.StaticLog; import fr.neatmonster.nocheatplus.logging.StaticLog;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.permissions.Permissions; import fr.neatmonster.nocheatplus.permissions.Permissions;
import fr.neatmonster.nocheatplus.players.DataManager; import fr.neatmonster.nocheatplus.players.DataManager;
import fr.neatmonster.nocheatplus.stats.Counters; import fr.neatmonster.nocheatplus.stats.Counters;
@ -400,7 +401,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
earlyReturn = true; earlyReturn = true;
} else if (player.isSleeping()) { } else if (player.isSleeping()) {
// Ignore sleeping playerrs. // Ignore sleeping playerrs.
// TODO: sleeping: (which cb!) System.out.println("-> " + player.isSleepingIgnored()); // TODO: sleeping: (which cb!) NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "-> " + player.isSleepingIgnored());
data.sfHoverTicks = -1; data.sfHoverTicks = -1;
earlyReturn = true; earlyReturn = true;
} else if (!from.getWorld().equals(to.getWorld())) { } else if (!from.getWorld().equals(to.getWorld())) {
@ -694,7 +695,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// Debug. // Debug.
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " set back to: " + newTo.getWorld() + StringUtil.fdec3.format(newTo.getX()) + ", " + StringUtil.fdec3.format(newTo.getY()) + ", " + StringUtil.fdec3.format(newTo.getZ())); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " set back to: " + newTo.getWorld() + StringUtil.fdec3.format(newTo.getX()) + ", " + StringUtil.fdec3.format(newTo.getY()) + ", " + StringUtil.fdec3.format(newTo.getZ()));
} }
} }
@ -981,7 +982,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
} }
if (cc.debug && BuildParameters.debugLevel > 0) { if (cc.debug && BuildParameters.debugLevel > 0) {
System.out.println(player.getName() + " TP" + (smallRange ? " (small-range)" : "") + (cancel ? " (cancelled)" : "") + ": " + to); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " TP" + (smallRange ? " (small-range)" : "") + (cancel ? " (cancelled)" : "") + ": " + to);
} }
} }
else{ else{
@ -989,7 +990,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// Better reset teleported (compatibility). Might have drawbacks. // Better reset teleported (compatibility). Might have drawbacks.
data.resetTeleported(); data.resetTeleported();
if (cc.debug && BuildParameters.debugLevel > 0) { if (cc.debug && BuildParameters.debugLevel > 0) {
System.out.println(player.getName() + " TP (cancelled): " + to); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " TP (cancelled): " + to);
} }
return; return;
} }
@ -1028,7 +1029,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
final Vector velocity = event.getVelocity(); final Vector velocity = event.getVelocity();
if (cc.debug) { if (cc.debug) {
System.out.println(event.getPlayer().getName() + " new velocity: " + velocity); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, event.getPlayer().getName() + " new velocity: " + velocity);
} }
double newVal = velocity.getY(); double newVal = velocity.getY();
@ -1078,7 +1079,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// A little extra sweep to check for debug flags. // A little extra sweep to check for debug flags.
normalVehicles.add(entityType); normalVehicles.add(entityType);
if (MovingConfig.getConfig(vehicle.getWorld().getName()).debug) { if (MovingConfig.getConfig(vehicle.getWorld().getName()).debug) {
System.out.println("[NoCheatPlus] VehicleMoveEvent fired for: " + entityType); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, "[NoCheatPlus] VehicleMoveEvent fired for: " + entityType);
} }
} }
// TODO: Might account for the case of a player letting the vehicle move but not themself (do mind latency). // TODO: Might account for the case of a player letting the vehicle move but not themself (do mind latency).
@ -1213,7 +1214,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
final double damage = BridgeHealth.getDamage(event); final double damage = BridgeHealth.getDamage(event);
final float yDiff = (float) (data.noFallMaxY - loc.getY()); final float yDiff = (float) (data.noFallMaxY - loc.getY());
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " damage(FALL): " + damage + " / dist=" + player.getFallDistance() + " nf=" + data.noFallFallDistance + " yDiff=" + yDiff); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " damage(FALL): " + damage + " / dist=" + player.getFallDistance() + " nf=" + data.noFallFallDistance + " yDiff=" + yDiff);
} }
// Fall-back check. // Fall-back check.
final double maxD = NoFall.getDamage(Math.max(yDiff, Math.max(data.noFallFallDistance, fallDistance))) + (allowReset ? 0.0 : 3.0); final double maxD = NoFall.getDamage(Math.max(yDiff, Math.max(data.noFallFallDistance, fallDistance))) + (allowReset ? 0.0 : 3.0);
@ -1221,7 +1222,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// TODO: respect dealDamage ? // TODO: respect dealDamage ?
BridgeHealth.setDamage(event, maxD); BridgeHealth.setDamage(event, maxD);
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " Adjust fall damage to: " + maxD); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " Adjust fall damage to: " + maxD);
} }
} }
if (allowReset) { if (allowReset) {
@ -1487,7 +1488,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
} }
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " vehicle leave: " + vehicle.getType() + "@" + pLoc.distance(vLoc)); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " vehicle leave: " + vehicle.getType() + "@" + pLoc.distance(vLoc));
} }
} }
@ -1497,7 +1498,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
} }
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " vehicle leave: " + pLoc.toString() + (pLoc.equals(loc) ? "" : " / player at: " + pLoc.toString())); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " vehicle leave: " + pLoc.toString() + (pLoc.equals(loc) ? "" : " / player at: " + pLoc.toString()));
} }
data.resetPositions(loc); data.resetPositions(loc);
data.setSetBack(loc); data.setSetBack(loc);

View File

@ -7,9 +7,11 @@ import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.checks.Check; import fr.neatmonster.nocheatplus.checks.Check;
import fr.neatmonster.nocheatplus.checks.CheckType; import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.compat.BridgeHealth; import fr.neatmonster.nocheatplus.compat.BridgeHealth;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.utilities.PlayerLocation; import fr.neatmonster.nocheatplus.utilities.PlayerLocation;
import fr.neatmonster.nocheatplus.utilities.StringUtil; import fr.neatmonster.nocheatplus.utilities.StringUtil;
@ -52,7 +54,9 @@ public class NoFall extends Check {
if (maxD >= 1.0){ if (maxD >= 1.0){
// Damage to be dealt. // Damage to be dealt.
// TODO: more effects like sounds, maybe use custom event with violation added. // TODO: more effects like sounds, maybe use custom event with violation added.
if (cc.debug) System.out.println(player.getName() + " NoFall deal damage" + (reallyOnGround ? "" : "violation") + ": " + maxD); if (cc.debug) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " NoFall deal damage" + (reallyOnGround ? "" : "violation") + ": " + maxD);
}
// TODO: might not be necessary: if (mcPlayer.invulnerableTicks <= 0) [no damage event for resetting] // TODO: might not be necessary: if (mcPlayer.invulnerableTicks <= 0) [no damage event for resetting]
data.noFallSkipAirCheck = true; data.noFallSkipAirCheck = true;
dealFallDamage(player, maxD); dealFallDamage(player, maxD);
@ -171,7 +175,7 @@ public class NoFall extends Check {
final double max = Math.max(data.noFallFallDistance, mcFallDistance); final double max = Math.max(data.noFallFallDistance, mcFallDistance);
if (max > 0.0 && max < 0.75){ // (Ensure this does not conflict with deal-damage set to false.) if (max > 0.0 && max < 0.75){ // (Ensure this does not conflict with deal-damage set to false.)
if (cc.debug){ if (cc.debug){
System.out.println(player.getName() + " NoFall: Reset fall distance (anticriticals): mc=" + StringUtil.fdec3.format(mcFallDistance) +" / nf=" + StringUtil.fdec3.format(data.noFallFallDistance) ); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " NoFall: Reset fall distance (anticriticals): mc=" + StringUtil.fdec3.format(mcFallDistance) +" / nf=" + StringUtil.fdec3.format(data.noFallFallDistance) );
} }
if (data.noFallFallDistance > 0){ if (data.noFallFallDistance > 0){
data.noFallFallDistance = 0; data.noFallFallDistance = 0;
@ -183,7 +187,7 @@ public class NoFall extends Check {
} }
if (cc.debug){ if (cc.debug){
System.out.println(player.getName() + " NoFall: mc=" + StringUtil.fdec3.format(mcFallDistance) +" / nf=" + StringUtil.fdec3.format(data.noFallFallDistance) + (oldNFDist < data.noFallFallDistance ? " (+" + StringUtil.fdec3.format(data.noFallFallDistance - oldNFDist) + ")" : "") + " | ymax=" + StringUtil.fdec3.format(data.noFallMaxY)); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " NoFall: mc=" + StringUtil.fdec3.format(mcFallDistance) +" / nf=" + StringUtil.fdec3.format(data.noFallFallDistance) + (oldNFDist < data.noFallFallDistance ? " (+" + StringUtil.fdec3.format(data.noFallFallDistance - oldNFDist) + ")" : "") + " | ymax=" + StringUtil.fdec3.format(data.noFallMaxY));
} }
} }

View File

@ -5,10 +5,12 @@ import java.util.Locale;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.actions.ParameterName; import fr.neatmonster.nocheatplus.actions.ParameterName;
import fr.neatmonster.nocheatplus.checks.Check; import fr.neatmonster.nocheatplus.checks.Check;
import fr.neatmonster.nocheatplus.checks.CheckType; import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.ViolationData; import fr.neatmonster.nocheatplus.checks.ViolationData;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.utilities.BlockProperties; import fr.neatmonster.nocheatplus.utilities.BlockProperties;
import fr.neatmonster.nocheatplus.utilities.PassableRayTracing; import fr.neatmonster.nocheatplus.utilities.PassableRayTracing;
import fr.neatmonster.nocheatplus.utilities.PlayerLocation; import fr.neatmonster.nocheatplus.utilities.PlayerLocation;
@ -56,7 +58,7 @@ public class Passable extends Check {
tags = "raytracing_2x_"; tags = "raytracing_2x_";
} }
else if (cc.debug) { else if (cc.debug) {
System.out.println(player.getName() + " passable: allow moving out of a block."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " passable: allow moving out of a block.");
} }
} }
else{ else{
@ -147,10 +149,10 @@ public class Passable extends Check {
// if (BlockProperties.isPassableExact(from.getBlockCache(), ref)) { // if (BlockProperties.isPassableExact(from.getBlockCache(), ref)) {
loc = ref; loc = ref;
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " Using set-back location for passable."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " Using set-back location for passable.");
} }
} else if (cc.debug) { } else if (cc.debug) {
System.out.println(player.getName() + " Ignoring set-back for passable."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " Ignoring set-back for passable.");
} }
} }
@ -178,7 +180,7 @@ public class Passable extends Check {
} else { } else {
newTo = from.getLocation(); newTo = from.getLocation();
if (cc.debug) { if (cc.debug) {
System.out.println(player.getName() + " Using from location for passable."); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " Using from location for passable.");
} }
} }
newTo.setYaw(to.getYaw()); newTo.setYaw(to.getYaw());

View File

@ -9,10 +9,12 @@ import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.actions.ParameterName; import fr.neatmonster.nocheatplus.actions.ParameterName;
import fr.neatmonster.nocheatplus.checks.Check; import fr.neatmonster.nocheatplus.checks.Check;
import fr.neatmonster.nocheatplus.checks.CheckType; import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.ViolationData; import fr.neatmonster.nocheatplus.checks.ViolationData;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.permissions.Permissions; import fr.neatmonster.nocheatplus.permissions.Permissions;
import fr.neatmonster.nocheatplus.utilities.ActionAccumulator; import fr.neatmonster.nocheatplus.utilities.ActionAccumulator;
import fr.neatmonster.nocheatplus.utilities.BlockProperties; import fr.neatmonster.nocheatplus.utilities.BlockProperties;
@ -473,7 +475,7 @@ public class SurvivalFly extends Check {
if (hDistance <= (cc.velocityStrictInvalidation ? hAllowedDistance : hAllowedDistance / 2.0)) { if (hDistance <= (cc.velocityStrictInvalidation ? hAllowedDistance : hAllowedDistance / 2.0)) {
// TODO: Should there be other side conditions? // TODO: Should there be other side conditions?
// Invalidate used horizontal velocity. // Invalidate used horizontal velocity.
// System.out.println("*** INVALIDATE ON SPEED"); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** INVALIDATE ON SPEED");
data.clearActiveHorVel(); data.clearActiveHorVel();
// if (data.horizontalVelocityUsed > cc.velocityGraceTicks) { // if (data.horizontalVelocityUsed > cc.velocityGraceTicks) {
// data.horizontalFreedom = 0; // data.horizontalFreedom = 0;
@ -1422,7 +1424,7 @@ public class SurvivalFly extends Check {
if (!tags.isEmpty()) builder.append("\n" + " tags: " + StringUtil.join(tags, "+")); if (!tags.isEmpty()) builder.append("\n" + " tags: " + StringUtil.join(tags, "+"));
builder.append("\n"); builder.append("\n");
// builder.append(data.stats.getStatsStr(false)); // builder.append(data.stats.getStatsStr(false));
System.out.print(builder.toString()); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
} }
} }

View File

@ -1,6 +1,5 @@
package fr.neatmonster.nocheatplus.command.admin; package fr.neatmonster.nocheatplus.command.admin;
import java.io.File;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -10,6 +9,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.checks.CheckType; import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.command.BaseCommand; import fr.neatmonster.nocheatplus.command.BaseCommand;
import fr.neatmonster.nocheatplus.command.NoCheatPlusCommand.NCPReloadEvent; import fr.neatmonster.nocheatplus.command.NoCheatPlusCommand.NCPReloadEvent;
@ -18,7 +18,8 @@ import fr.neatmonster.nocheatplus.components.order.Order;
import fr.neatmonster.nocheatplus.config.ConfPaths; import fr.neatmonster.nocheatplus.config.ConfPaths;
import fr.neatmonster.nocheatplus.config.ConfigFile; import fr.neatmonster.nocheatplus.config.ConfigFile;
import fr.neatmonster.nocheatplus.config.ConfigManager; import fr.neatmonster.nocheatplus.config.ConfigManager;
import fr.neatmonster.nocheatplus.logging.StaticLogFile; import fr.neatmonster.nocheatplus.logging.LogManager;
import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.permissions.Permissions; import fr.neatmonster.nocheatplus.permissions.Permissions;
import fr.neatmonster.nocheatplus.players.DataManager; import fr.neatmonster.nocheatplus.players.DataManager;
@ -48,13 +49,17 @@ public class ReloadCommand extends BaseCommand {
* @return true, if successful * @return true, if successful
*/ */
private void handleReloadCommand(final CommandSender sender) { private void handleReloadCommand(final CommandSender sender) {
final LogManager logManager = NCPAPIProvider.getNoCheatPlusAPI().getLogManager();
if (!sender.equals(Bukkit.getConsoleSender())) {
sender.sendMessage(TAG + "Reloading configuration..."); sender.sendMessage(TAG + "Reloading configuration...");
}
logManager.info(Streams.INIT, "[NoCheatPlus] Reloading configuration...");
// Do the actual reload. // Do the actual reload.
ConfigManager.cleanup(); ConfigManager.cleanup();
ConfigManager.init(access); ConfigManager.init(access);
StaticLogFile.cleanup(); logManager.onReload(); // Does not get exchanged (!).
StaticLogFile.setupLogger(new File(access.getDataFolder(), ConfigManager.getConfigFile().getString(ConfPaths.LOGGING_BACKEND_FILE_FILENAME)));
// Remove all cached configs. // Remove all cached configs.
DataManager.clearConfigs(); // There you have to add XConfig.clear() form now on. DataManager.clearConfigs(); // There you have to add XConfig.clear() form now on.
// Remove some checks data. // Remove some checks data.
@ -73,11 +78,11 @@ public class ReloadCommand extends BaseCommand {
// Say to the other plugins that we've reloaded the configuration. // Say to the other plugins that we've reloaded the configuration.
Bukkit.getPluginManager().callEvent(new NCPReloadEvent()); Bukkit.getPluginManager().callEvent(new NCPReloadEvent());
// Log reloading done.
if (!sender.equals(Bukkit.getConsoleSender())) {
sender.sendMessage(TAG + "Configuration reloaded!"); sender.sendMessage(TAG + "Configuration reloaded!");
final String info = "[NoCheatPlus] Configuration reloaded."; }
if (!(sender instanceof ConsoleCommandSender)) Bukkit.getLogger().info(info); logManager.info(Streams.INIT, "[NoCheatPlus] Configuration reloaded.");
final ConfigFile config = ConfigManager.getConfigFile();
if (config.getBoolean(ConfPaths.LOGGING_ACTIVE) && config.getBoolean(ConfPaths.LOGGING_BACKEND_FILE_ACTIVE)) StaticLogFile.fileLogger.info(info);
} }
} }

View File

@ -1,5 +1,7 @@
package fr.neatmonster.nocheatplus.components; package fr.neatmonster.nocheatplus.components;
import fr.neatmonster.nocheatplus.logging.LogManager;
/** /**
@ -83,4 +85,11 @@ public interface NoCheatPlusAPI extends ComponentRegistry<Object>, ComponentRegi
* @return * @return
*/ */
public boolean isLoginDenied(String playerName, long time); public boolean isLoginDenied(String playerName, long time);
/**
* Get the central access point for logging (LogManager),
* @return
*/
public LogManager getLogManager();
} }

View File

@ -29,6 +29,7 @@ public abstract class ConfPaths {
private static final String LOGGING = "logging."; private static final String LOGGING = "logging.";
public static final String LOGGING_ACTIVE = LOGGING + "active"; public static final String LOGGING_ACTIVE = LOGGING + "active";
public static final String LOGGING_DEBUG = LOGGING + "debug"; public static final String LOGGING_DEBUG = LOGGING + "debug";
public static final String LOGGING_MAXQUEUESIZE = LOGGING + "maxqueuesize";
private static final String LOGGING_BACKEND = LOGGING + "backend."; private static final String LOGGING_BACKEND = LOGGING + "backend.";
private static final String LOGGING_BACKEND_CONSOLE = LOGGING_BACKEND + "console."; private static final String LOGGING_BACKEND_CONSOLE = LOGGING_BACKEND + "console.";

View File

@ -52,6 +52,8 @@ public class ConfigManager {
}; };
private static boolean isInitialized = false;
/** /**
* Factory method. * Factory method.
* @param library * @param library
@ -114,8 +116,9 @@ public class ConfigManager {
* Cleanup. * Cleanup.
*/ */
public static void cleanup() { public static void cleanup() {
isInitialized = false;
setActionFactoryFactory(null); setActionFactoryFactory(null);
// TODO: Remove references of config files ?
} }
/** /**
@ -266,6 +269,15 @@ public class ConfigManager {
// worldConfig.setActionFactory(); // worldConfig.setActionFactory();
} }
ConfigManager.worldsMap = newWorldsMap; ConfigManager.worldsMap = newWorldsMap;
isInitialized = true;
}
/**
* Informal test if the init method completed (no details are reflected).
* @return
*/
public static boolean isInitialized() {
return isInitialized;
} }
/** /**

View File

@ -7,6 +7,7 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.compat.MCAccess; import fr.neatmonster.nocheatplus.compat.MCAccess;
import fr.neatmonster.nocheatplus.utilities.BlockProperties; import fr.neatmonster.nocheatplus.utilities.BlockProperties;
import fr.neatmonster.nocheatplus.utilities.PlayerLocation; import fr.neatmonster.nocheatplus.utilities.PlayerLocation;
@ -216,7 +217,7 @@ public class DebugUtil {
builder.append(" (" + (speed != Double.NEGATIVE_INFINITY ? ("e_speed=" + (speed + 1)) : "") + (jump != Double.NEGATIVE_INFINITY ? ("e_jump=" + (jump + 1)) : "") + ")"); builder.append(" (" + (speed != Double.NEGATIVE_INFINITY ? ("e_speed=" + (speed + 1)) : "") + (jump != Double.NEGATIVE_INFINITY ? ("e_jump=" + (jump + 1)) : "") + ")");
} }
// Print basic info first in order // Print basic info first in order
System.out.print(builder.toString()); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
// Extended info. // Extended info.
if (BuildParameters.debugLevel > 0){ if (BuildParameters.debugLevel > 0){
builder.setLength(0); builder.setLength(0);
@ -231,7 +232,7 @@ public class DebugUtil {
if (to.getTypeId() != 0) addBlockInfo(builder, to, "\nto"); if (to.getTypeId() != 0) addBlockInfo(builder, to, "\nto");
if (to.getTypeIdBelow() != 0) addBlockBelowInfo(builder, to, "\nto"); if (to.getTypeIdBelow() != 0) addBlockBelowInfo(builder, to, "\nto");
if (!to.isOnGround() && to.isOnGround(0.5)) builder.append(" (ground within 0.5)"); if (!to.isOnGround() && to.isOnGround(0.5)) builder.append(" (ground within 0.5)");
System.out.print(builder.toString()); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
} }
} }
@ -278,7 +279,7 @@ public class DebugUtil {
addFormattedLocation(loc, builder); addFormattedLocation(loc, builder);
} }
builder.append("\n Vehicle type: " + vehicle.getType() + (wrongVehicle ? (actualVehicle == null ? " (exited?)" : " actual: " + actualVehicle.getType()) : "")); builder.append("\n Vehicle type: " + vehicle.getType() + (wrongVehicle ? (actualVehicle == null ? " (exited?)" : " actual: " + actualVehicle.getType()) : ""));
System.out.print(builder.toString()); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
} }
} }

View File

@ -4,18 +4,19 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.Bukkit; import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.utilities.StringUtil; import fr.neatmonster.nocheatplus.utilities.StringUtil;
/** /**
* Static access methods for more or less direct logging using either Bukkit.getLogger() or System.out. * Static access methods for more or less direct logging using either LogManager/INIT or System.out.
* @author mc_dev * @author mc_dev
* *
*/ */
public class StaticLog { public class StaticLog {
private static boolean useBukkitLogger = true; // TODO: Remove this class (needs a version of LogManager for testing, i.e. ).
private static boolean useBukkitLogger = false; // Let the plugin control this.
/** /**
* This is for testing purposes only. * This is for testing purposes only.
@ -57,7 +58,7 @@ public class StaticLog {
public static void log(final Level level, final String msg) { public static void log(final Level level, final String msg) {
if (useBukkitLogger) { if (useBukkitLogger) {
Bukkit.getLogger().log(level, msg); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().log(Streams.INIT, level, msg);
} else { } else {
System.out.println("[" + level + "] " + new Date()); System.out.println("[" + level + "] " + new Date());
System.out.println(msg); System.out.println(msg);
@ -107,30 +108,21 @@ public class StaticLog {
} }
/** /**
* Schedule a log message with given level for the Bukkit logger with the NoCheatPlus plugin.<br> * Same as log(level, message).
*
* @deprecated Same as log(level, message).
* *
* @param level * @param level
* @param message * @param message
* @return * @return
*/ */
public static boolean scheduleLog(final Level level, final String message) { public static boolean scheduleLog(final Level level, final String message) {
if (!useBukkitLogger) {
return false;
}
try {
return Bukkit.getScheduler().scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("NoCheatPlus"), new Runnable() {
@Override
public final void run() {
StaticLog.log(level, message); StaticLog.log(level, message);
} return true;
}) != -1;
} catch (final Exception exc) {
return false;
}
} }
/** /**
* Schedule joined parts for info level. * Log joined parts on info level.
* @param level * @param level
* @param parts * @param parts
* @param link * @param link
@ -142,7 +134,7 @@ public class StaticLog {
} }
/** /**
* Schedule joined. * Log joined parts on the given level.
* @param level * @param level
* @param parts * @param parts
* @param link * @param link

View File

@ -2344,7 +2344,7 @@ public class BlockProperties {
final int iMaxY = Math.min(Location.locToBlock(maxY), maxBlockY); final int iMaxY = Math.min(Location.locToBlock(maxY), maxBlockY);
final int iMinZ = Location.locToBlock(minZ); final int iMinZ = Location.locToBlock(minZ);
final int iMaxZ = Location.locToBlock(maxZ); final int iMaxZ = Location.locToBlock(maxZ);
// System.out.println("*** isOnGround check size: " + ((iMaxX - iMinX + 1) * (iMaxY - iMinY + 1) * (iMaxZ - iMinZ + 1))); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** isOnGround check size: " + ((iMaxX - iMinX + 1) * (iMaxY - iMinY + 1) * (iMaxZ - iMinZ + 1)));
for (int x = iMinX; x <= iMaxX; x++) { for (int x = iMinX; x <= iMaxX; x++) {
for (int z = iMinZ; z <= iMaxZ; z++) { for (int z = iMinZ; z <= iMaxZ; z++) {
@ -2601,7 +2601,7 @@ public class BlockProperties {
final int iMaxY = Location.locToBlock(maxY); final int iMaxY = Location.locToBlock(maxY);
final int iMinZ = Location.locToBlock(minZ); final int iMinZ = Location.locToBlock(minZ);
final int iMaxZ = Location.locToBlock(maxZ); final int iMaxZ = Location.locToBlock(maxZ);
// System.out.println("*** collect flags check size: " + ((iMaxX - iMinX + 1) * (iMaxY - iMinY + 1) * (iMaxZ - iMinZ + 1))); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** collect flags check size: " + ((iMaxX - iMinX + 1) * (iMaxY - iMinY + 1) * (iMaxZ - iMinZ + 1)));
long flags = 0; long flags = 0;
for (int x = iMinX; x <= iMaxX; x++) { for (int x = iMinX; x <= iMaxX; x++) {
for (int z = iMinZ; z <= iMaxZ; z++) { for (int z = iMinZ; z <= iMaxZ; z++) {

View File

@ -487,13 +487,13 @@ public class PlayerLocation {
// TODO: BlockHeight is needed for fences, use right away (above)? // TODO: BlockHeight is needed for fences, use right away (above)?
if (!BlockProperties.isPassableWorkaround(blockCache, blockX, bY, blockZ, minX - blockX, minY - yOnGround - bY, minZ - blockZ, id, maxX - minX, yOnGround, maxZ - minZ, 1.0) if (!BlockProperties.isPassableWorkaround(blockCache, blockX, bY, blockZ, minX - blockX, minY - yOnGround - bY, minZ - blockZ, id, maxX - minX, yOnGround, maxZ - minZ, 1.0)
|| (flags & BlockProperties.F_GROUND_HEIGHT) != 0 && BlockProperties.getGroundMinHeight(blockCache, blockX, bY, blockZ, id, bounds, flags) <= y - bY) { || (flags & BlockProperties.F_GROUND_HEIGHT) != 0 && BlockProperties.getGroundMinHeight(blockCache, blockX, bY, blockZ, id, bounds, flags) <= y - bY) {
// System.out.println("*** onground SHORTCUT"); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** onground SHORTCUT");
onGround = true; onGround = true;
} }
} }
} }
if (onGround == null) { if (onGround == null) {
// System.out.println("*** fetch onground std"); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** fetch onground std");
// Full on-ground check (blocks). // Full on-ground check (blocks).
// Note: Might check for half-block height too (getTypeId), but that is much more seldom. // Note: Might check for half-block height too (getTypeId), but that is much more seldom.
onGround = BlockProperties.isOnGround(blockCache, minX, minY - yOnGround, minZ, maxX, minY, maxZ, 0L); onGround = BlockProperties.isOnGround(blockCache, minX, minY - yOnGround, minZ, maxX, minY, maxZ, 0L);
@ -503,7 +503,7 @@ public class PlayerLocation {
} }
if (onGround) onGroundMinY = Math.min(onGroundMinY, yOnGround); if (onGround) onGroundMinY = Math.min(onGroundMinY, yOnGround);
else { else {
// System.out.println("*** onground check entities"); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** onground check entities");
// TODO: further confine this ? // TODO: further confine this ?
notOnGroundMaxY = Math.max(notOnGroundMaxY, yOnGround); notOnGroundMaxY = Math.max(notOnGroundMaxY, yOnGround);
final double d1 = 0.25D; final double d1 = 0.25D;
@ -568,7 +568,7 @@ public class PlayerLocation {
if (notOnGroundMaxY >= yOnGround) return false; if (notOnGroundMaxY >= yOnGround) return false;
} }
} }
// System.out.println("*** Fetch on-ground: yOnGround=" + yOnGround + " xzM=" + xzMargin + " yM=" + yMargin + " ign=" + ignoreFlags); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "*** Fetch on-ground: yOnGround=" + yOnGround + " xzM=" + xzMargin + " yM=" + yMargin + " ign=" + ignoreFlags);
final boolean onGround = BlockProperties.isOnGround(blockCache, minX - xzMargin, minY - yOnGround - yMargin, minZ - xzMargin, maxX + xzMargin, minY + yMargin, maxZ + xzMargin, ignoreFlags); final boolean onGround = BlockProperties.isOnGround(blockCache, minX - xzMargin, minY - yOnGround - yMargin, minZ - xzMargin, maxX + xzMargin, minY + yMargin, maxZ + xzMargin, ignoreFlags);
if (ignoreFlags == 0) { if (ignoreFlags == 0) {
if (onGround) { if (onGround) {

View File

@ -5,6 +5,9 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.logging.Streams;
public class TeleportUtil { public class TeleportUtil {
/** Temp use. LocUtil.clone on passing. setWorld(null) after use. */ /** Temp use. LocUtil.clone on passing. setWorld(null) after use. */
@ -39,7 +42,7 @@ public class TeleportUtil {
vehicle.setPassenger(player); vehicle.setPassenger(player);
} }
if (debug){ if (debug){
System.out.println(player.getName() + " vehicle set back: " + location); NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, player.getName() + " vehicle set back: " + location);
} }
useLoc.setWorld(null); useLoc.setWorld(null);
} }

View File

@ -104,7 +104,7 @@ public class TrigUtil {
{ {
// // TODO: Here we have 0.x vs. 2.x, sometimes ! // // TODO: Here we have 0.x vs. 2.x, sometimes !
// System.out.println("COMBINED: " + combinedDirectionCheck(sourceX, sourceY, sourceZ, dirX, dirY, dirZ, targetX, targetY, targetZ, targetWidth, targetHeight, precision, 60)); // NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(LogManager.TRACE_FILE, "COMBINED: " + combinedDirectionCheck(sourceX, sourceY, sourceZ, dirX, dirY, dirZ, targetX, targetY, targetZ, targetWidth, targetHeight, precision, 60));
// TODO: rework / standardize. // TODO: rework / standardize.

View File

@ -1,6 +1,5 @@
package fr.neatmonster.nocheatplus; package fr.neatmonster.nocheatplus;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -13,6 +12,7 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -69,8 +69,9 @@ import fr.neatmonster.nocheatplus.config.ConfigManager;
import fr.neatmonster.nocheatplus.event.IHaveMethodOrder; import fr.neatmonster.nocheatplus.event.IHaveMethodOrder;
import fr.neatmonster.nocheatplus.event.ListenerManager; import fr.neatmonster.nocheatplus.event.ListenerManager;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
import fr.neatmonster.nocheatplus.logging.LogManager;
import fr.neatmonster.nocheatplus.logging.StaticLog; import fr.neatmonster.nocheatplus.logging.StaticLog;
import fr.neatmonster.nocheatplus.logging.StaticLogFile; import fr.neatmonster.nocheatplus.logging.Streams;
import fr.neatmonster.nocheatplus.permissions.PermissionUtil; import fr.neatmonster.nocheatplus.permissions.PermissionUtil;
import fr.neatmonster.nocheatplus.permissions.PermissionUtil.CommandProtectionEntry; import fr.neatmonster.nocheatplus.permissions.PermissionUtil.CommandProtectionEntry;
import fr.neatmonster.nocheatplus.permissions.Permissions; import fr.neatmonster.nocheatplus.permissions.Permissions;
@ -105,6 +106,9 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Not static. // Not static.
/** Central logging access point. */
private LogManager logManager = null; // Not final, but intended to stay, once set [change to init=syso?].
/** Names of players with a certain permission. */ /** Names of players with a certain permission. */
protected final NameSetPermState nameSetPerms = new NameSetPermState(Permissions.NOTIFY); protected final NameSetPermState nameSetPerms = new NameSetPermState(Permissions.NOTIFY);
@ -469,7 +473,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
if (listener instanceof IHaveMethodOrder){ if (listener instanceof IHaveMethodOrder){
// TODO: Might log the order too, might prevent registration ? // TODO: Might log the order too, might prevent registration ?
// TODO: Alternative: queue listeners and register after startup (!) // TODO: Alternative: queue listeners and register after startup (!)
StaticLog.logWarning("[NoCheatPlus] Listener demands registration order, but listeners are not managed: " + listener.getClass().getName()); logManager.warning(Streams.INIT, "[NoCheatPlus] Listener demands registration order, but listeners are not managed: " + listener.getClass().getName());
} }
} }
} }
@ -530,10 +534,10 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Remove listener references. // Remove listener references.
if (verbose){ if (verbose){
if (listenerManager.hasListenerMethods()) { if (listenerManager.hasListenerMethods()) {
StaticLog.logInfo("[NoCheatPlus] Cleanup ListenerManager..."); logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup ListenerManager...");
} }
else { else {
StaticLog.logInfo("[NoCheatPlus] (ListenerManager not in use, prevent registering...)"); logManager.info(Streams.INIT, "[NoCheatPlus] (ListenerManager not in use, prevent registering...)");
} }
} }
listenerManager.setRegisterDirectly(false); listenerManager.setRegisterDirectly(false);
@ -549,7 +553,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Stop the tickTask. // Stop the tickTask.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Stop TickTask..."); logManager.info(Streams.INIT, "[NoCheatPlus] Stop TickTask...");
} }
TickTask.setLocked(true); TickTask.setLocked(true);
TickTask.purge(); TickTask.purge();
@ -565,34 +569,34 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Just to be sure nothing gets left out. // Just to be sure nothing gets left out.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Stop all remaining tasks..."); logManager.info(Streams.INIT, "[NoCheatPlus] Stop all remaining tasks...");
} }
sched.cancelTasks(this); sched.cancelTasks(this);
// Exemptions cleanup. // Exemptions cleanup.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Reset ExemptionManager..."); logManager.info(Streams.INIT, "[NoCheatPlus] Reset ExemptionManager...");
} }
NCPExemptionManager.clear(); NCPExemptionManager.clear();
// Data cleanup. // Data cleanup.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] onDisable calls (include DataManager cleanup)..."); logManager.info(Streams.INIT, "[NoCheatPlus] onDisable calls (include DataManager cleanup)...");
} }
for (final DisableListener dl : disableListeners) { for (final DisableListener dl : disableListeners) {
try { try {
dl.onDisable(); dl.onDisable();
} catch (Throwable t) { } catch (Throwable t) {
// bad :) // bad :)
StaticLog.logSevere("DisableListener (" + dl.getClass().getName() + "): " + t.getClass().getSimpleName() + " / " + t.getMessage()); logManager.severe(Streams.INIT, "DisableListener (" + dl.getClass().getName() + "): " + t.getClass().getSimpleName() + " / " + t.getMessage());
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
} }
// Write some debug/statistics. // Write some debug/statistics.
final Counters counters = getGenericInstance(Counters.class); final Counters counters = getGenericInstance(Counters.class);
if (verbose && counters != null) { if (verbose && counters != null) {
StaticLog.logInfo(counters.getMergedCountsString(true)); logManager.info(Streams.INIT, counters.getMergedCountsString(true));
} }
// Hooks: // Hooks:
@ -601,7 +605,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Unregister all added components explicitly. // Unregister all added components explicitly.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Unregister all registered components..."); logManager.info(Streams.INIT, "[NoCheatPlus] Unregister all registered components...");
} }
final ArrayList<Object> allComponents = new ArrayList<Object>(this.allComponents); final ArrayList<Object> allComponents = new ArrayList<Object>(this.allComponents);
for (int i = allComponents.size() - 1; i >= 0; i--){ for (int i = allComponents.size() - 1; i >= 0; i--){
@ -610,12 +614,12 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Cleanup BlockProperties. // Cleanup BlockProperties.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Cleanup BlockProperties..."); logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup BlockProperties...");
} }
BlockProperties.cleanup(); BlockProperties.cleanup();
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Cleanup some mappings..."); logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup some mappings...");
} }
// Remove listeners. // Remove listeners.
listeners.clear(); listeners.clear();
@ -641,22 +645,23 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Cleanup the configuration manager. // Cleanup the configuration manager.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Cleanup ConfigManager..."); logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup ConfigManager...");
} }
ConfigManager.cleanup(); ConfigManager.cleanup();
// Cleanup file logger. // Cleanup file logger.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] Cleanup file logger..."); logManager.info(Streams.INIT, "[NoCheatPlus] Shutdown LogManager...");
} }
StaticLogFile.cleanup(); StaticLog.setUseBukkitLogger(false);
logManager.shutdown();
// Tell the server administrator the we finished unloading NoCheatPlus. // Tell the server administrator the we finished unloading NoCheatPlus.
if (verbose) { if (verbose) {
StaticLog.logInfo("[NoCheatPlus] All cleanup done."); Bukkit.getLogger().info("[NoCheatPlus] All cleanup done.");
} }
final PluginDescriptionFile pdfFile = getDescription(); final PluginDescriptionFile pdfFile = getDescription();
StaticLog.logInfo("[NoCheatPlus] Version " + pdfFile.getVersion() + " is disabled."); Bukkit.getLogger().info("[NoCheatPlus] Version " + pdfFile.getVersion() + " is disabled.");
} }
/** /**
@ -706,7 +711,13 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
*/ */
@Override @Override
public void onLoad() { public void onLoad() {
Bukkit.getLogger().info("[NoCheatPlus] Setting up static API, config, logging.");
NCPAPIProvider.setNoCheatPlusAPI(this); NCPAPIProvider.setNoCheatPlusAPI(this);
// Read the configuration files.
ConfigManager.init(this); // TODO: Only load the bootstrap config (not all).
logManager = new LogManager(this);
StaticLog.setUseBukkitLogger(true);
logManager.info(Streams.INIT, "[NoCheatPlus] Logging system initialized.");
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -721,15 +732,17 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
TickTask.cancel(); TickTask.cancel();
TickTask.reset(); TickTask.reset();
// Start logger task(s).
logManager.startTasks();
// Register some generic stuff. // Register some generic stuff.
// Counters: debugging purposes, maybe integrated for statistics later. // Counters: debugging purposes, maybe integrated for statistics later.
registerGenericInstance(new Counters()); registerGenericInstance(new Counters());
// Read the configuration files. if (!ConfigManager.isInitialized()) {
// Read the configuration files (should only happen on reloading).
ConfigManager.init(this); ConfigManager.init(this);
}
// Setup file logger.
StaticLogFile.setupLogger(new File(getDataFolder(), ConfigManager.getConfigFile().getString(ConfPaths.LOGGING_BACKEND_FILE_FILENAME)));
final ConfigFile config = ConfigManager.getConfigFile(); final ConfigFile config = ConfigManager.getConfigFile();
@ -848,7 +861,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
configProblems = Updates.isConfigUpToDate(config); configProblems = Updates.isConfigUpToDate(config);
if (configProblems != null && config.getBoolean(ConfPaths.CONFIGVERSION_NOTIFY)){ if (configProblems != null && config.getBoolean(ConfPaths.CONFIGVERSION_NOTIFY)){
// Could use custom prefix from logging, however ncp should be mentioned then. // Could use custom prefix from logging, however ncp should be mentioned then.
StaticLog.logWarning("[NoCheatPlus] " + configProblems); logManager.warning(Streams.INIT, "[NoCheatPlus] " + configProblems);
} }
// Care for already online players. // Care for already online players.
@ -880,21 +893,21 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
}); });
// Tell the server administrator that we finished loading NoCheatPlus now. // Tell the server administrator that we finished loading NoCheatPlus now.
StaticLog.logInfo("[NoCheatPlus] Version " + getDescription().getVersion() + " is enabled."); logManager.info(Streams.INIT, "[NoCheatPlus] Version " + getDescription().getVersion() + " is enabled.");
} }
/** /**
* Actions to be done after enable of all plugins. This aims at reloading mainly. * Actions to be done after enable of all plugins. This aims at reloading mainly.
*/ */
private void postEnable(final Player[] onlinePlayers, Runnable... runnables){ private void postEnable(final Player[] onlinePlayers, Runnable... runnables){
StaticLog.logInfo("[NoCheatPlus] Post-enable running..."); logManager.info(Streams.INIT, "[NoCheatPlus] Post-enable running...");
for (final Runnable runnable : runnables){ for (final Runnable runnable : runnables){
try{ try{
runnable.run(); runnable.run();
} }
catch(Throwable t){ catch(Throwable t){
StaticLog.logSevere("[NoCheatPlus] Encountered a problem during post-enable: " + t.getClass().getSimpleName()); logManager.severe(Streams.INIT, "[NoCheatPlus] Encountered a problem during post-enable: " + t.getClass().getSimpleName());
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
} }
for (final Player player : onlinePlayers){ for (final Player player : onlinePlayers){
@ -905,7 +918,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
} }
} }
// TODO: if (online.lenght > 0) LogUtils.logInfo("[NCP] Updated " + online.length + "players (post-enable).") // TODO: if (online.lenght > 0) LogUtils.logInfo("[NCP] Updated " + online.length + "players (post-enable).")
StaticLog.logInfo("[NoCheatPlus] Post-enable finished."); logManager.info(Streams.INIT, "[NoCheatPlus] Post-enable finished.");
} }
/** /**
@ -944,6 +957,11 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
useSubscriptions = config.getBoolean(ConfPaths.LOGGING_BACKEND_INGAMECHAT_SUBSCRIPTIONS); useSubscriptions = config.getBoolean(ConfPaths.LOGGING_BACKEND_INGAMECHAT_SUBSCRIPTIONS);
} }
@Override
public LogManager getLogManager() {
return logManager;
}
@Override @Override
public MCAccess getMCAccess(){ public MCAccess getMCAccess(){
if (mcAccess == null) initMCAccess(); if (mcAccess == null) initMCAccess();
@ -988,12 +1006,12 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
try{ try{
((MCAccessHolder) obj).setMCAccess(mcAccess); ((MCAccessHolder) obj).setMCAccess(mcAccess);
} catch(Throwable t){ } catch(Throwable t){
StaticLog.logSevere("[NoCheatPlus] MCAccessHolder(" + obj.getClass().getName() + ") failed to set MCAccess: " + t.getClass().getSimpleName()); logManager.severe(Streams.INIT, "[NoCheatPlus] MCAccessHolder(" + obj.getClass().getName() + ") failed to set MCAccess: " + t.getClass().getSimpleName());
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
} }
} }
StaticLog.logInfo("[NoCheatPlus] McAccess set to: " + mcAccess.getMCVersion() + " / " + mcAccess.getServerVersionTag()); logManager.info(Streams.INIT, "[NoCheatPlus] McAccess set to: " + mcAccess.getMCVersion() + " / " + mcAccess.getServerVersionTag());
} }
/** /**
@ -1092,8 +1110,8 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
jlListener.playerJoins(player); jlListener.playerJoins(player);
} }
catch(Throwable t){ catch(Throwable t){
StaticLog.logSevere("[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (join): " + t.getClass().getSimpleName()); logManager.severe(Streams.INIT, "[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (join): " + t.getClass().getSimpleName());
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
} }
// Mod message (left on low instead of lowest to allow some permissions plugins compatibility). // Mod message (left on low instead of lowest to allow some permissions plugins compatibility).
@ -1109,8 +1127,8 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
jlListener.playerLeaves(player); jlListener.playerLeaves(player);
} }
catch(Throwable t){ catch(Throwable t){
StaticLog.logSevere("[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (leave): " + t.getClass().getSimpleName()); logManager.severe(Streams.INIT, "[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (leave): " + t.getClass().getSimpleName());
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
} }
} }
@ -1167,8 +1185,8 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
checker.checkConsistency(onlinePlayers); checker.checkConsistency(onlinePlayers);
} }
catch (Throwable t){ catch (Throwable t){
StaticLog.logSevere("[NoCheatPlus] ConsistencyChecker(" + checker.getClass().getName() + ") encountered an exception:"); logManager.severe(Streams.INIT, "[NoCheatPlus] ConsistencyChecker(" + checker.getClass().getName() + ") encountered an exception:");
StaticLog.logSevere(t); logManager.severe(Streams.INIT, t);
} }
consistencyCheckerIndex ++; // Do not remove :). consistencyCheckerIndex ++; // Do not remove :).
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
@ -1189,11 +1207,11 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
} }
}); });
if (debug){ if (debug){
StaticLog.logInfo("[NoCheatPlus] Re-scheduled consistency-checks."); logManager.info(Streams.TRACE_FILE, "[NoCheatPlus] Re-scheduled consistency-checks.");
} }
} }
else if (debug){ else if (debug){
StaticLog.logInfo("[NoCheatPlus] Consistency-checks run."); logManager.info(Streams.TRACE_FILE, "[NoCheatPlus] Consistency-checks run.");
} }
} }