Hello! I've made a simple logging class that displays messages to the console, and includes the line of code and class that called the log method: Code: public class LogUtils { public static final ChatColor ERROR_COLOR = ChatColor.RED; public static final ChatColor WARNING_COLOR = ChatColor.YELLOW; public static final ChatColor INFO_COLOR = ChatColor.BLUE; private LogUtils() {} public static void info(Object info) { String traceInfo = getTraceInfo(2); String msg = INFO_COLOR + "[INFO] " + ChatColor.RESET + info + " " + traceInfo; Bukkit.getConsoleSender().sendMessage(msg); } public static void error(Object error) { String traceInfo = getTraceInfo(2); String msg = ERROR_COLOR + "[ERROR] " + ChatColor.RESET + error + " " + traceInfo; Bukkit.getConsoleSender().sendMessage(msg); } public static void warning(Object warning) { String traceInfo = getTraceInfo(2); String msg = WARNING_COLOR + "[WARNING] " + ChatColor.RESET + warning + " " + traceInfo; Bukkit.getConsoleSender().sendMessage(msg); } private static String getTraceInfo(int methodSkip) { StackTraceElement stackTrace = new Throwable().getStackTrace()[methodSkip]; return "(" + stackTrace.getClassName() + ":" + stackTrace.getLineNumber() + ")"; } } In the error method, I usually send msg not only to the console, but also to the developers on the server. I find this very useful. For example, if you use the method "info" from line 43 of your class MyClass, this is some example output: Code: [INFO] Your message here. (path.to.MyClass:43) Thanks for reading.
@MCMastery You could make a general log method (just taking a String) and just reference it in the others. Will make changing the way it is logged later easier. But it looks quite useful
Uh no. Good for debugging, poor for production code. See http://stackoverflow.com/questions/299068/how-slow-are-java-exceptions: http://java-performance.info/throwing-an-exception-in-java-is-very-slow/ https://plumbr.eu/blog/java/throwing-exceptions-slow-and-ugly (btw the jmh test looks utterly moronic, don't even trust the numbers on it as there are multiple flaws that are out of scope of what I have to say) Conclusion: logging is a poor use of stack traces, should never ever be used in production code.
@xTrollxDudex Interesting read! Thank you. What would you propose? Entering a "logging section", where the method and possibly line numbers are supplied by the caller? Or is there a nice drop-in replacement (looking at why it occurs it is unlikely)?