Print debugging statement: Difference between revisions
Content added Content deleted
Line 218: | Line 218: | ||
value: &main.point{x:2, y:3} |
value: &main.point{x:2, y:3} |
||
</pre> |
</pre> |
||
=={{header|Java}}== |
|||
<lang java>import java.util.Objects; |
|||
public class PrintDebugStatement { |
|||
/** |
|||
* Takes advantage of the stack trace to determine locality for the calling function |
|||
* |
|||
* @param message the message to print |
|||
*/ |
|||
private static void printDebug(String message) { |
|||
Objects.requireNonNull(message); |
|||
RuntimeException exception = new RuntimeException(); |
|||
StackTraceElement[] stackTrace = exception.getStackTrace(); |
|||
// index 0 is this method, where the exception was created |
|||
// index 1 is the calling method, at the spot where this method was invoked |
|||
StackTraceElement stackTraceElement = stackTrace[1]; |
|||
String fileName = stackTraceElement.getFileName(); |
|||
String className = stackTraceElement.getClassName(); |
|||
String methodName = stackTraceElement.getMethodName(); |
|||
int lineNumber = stackTraceElement.getLineNumber(); |
|||
System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message); |
|||
} |
|||
private static void blah() { |
|||
printDebug("Made It!"); |
|||
} |
|||
public static void main(String[] args) { |
|||
printDebug("Hello world."); |
|||
blah(); |
|||
Runnable oops = () -> printDebug("oops"); |
|||
oops.run(); |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre>[DEBUG][PrintDebugStatement.java PrintDebugStatement.main#30] Hello world. |
|||
[DEBUG][PrintDebugStatement.java PrintDebugStatement.blah#26] Made It! |
|||
[DEBUG][PrintDebugStatement.java PrintDebugStatement.lambda$main$0#33] oops</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |