log method using stackTrace in Java
A custom log() method can used to print a message with a details like which class which function
called the log at which line number. It is useful for debugging.
1 public class Main {
2 public static void func() {
3 Log.log("\"log msg\"");
4 }
5
6 public static void main(String[] args) {
7 func();
8 Log.log("printing log in main");
9 }
10 }
11
12 class Log {
13
14 public static void log(String s) {
15 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
16 String className = stackTrace[2].getClassName();
17 String caller = stackTrace[2].getMethodName();
18 int lineNo = stackTrace[2].getLineNumber();
19 System.out.println("[class-name : " + className + "], [caller-function : "
20 + caller + "], [ line-no : "+ lineNo+ "], " + s);
21 }
22 }
Output:
[class-name : Main], [caller-function : func], [ line-no : 3], “log msg”
[class-name : Main], [caller-function : main], [ line-no : 8], printing log in main
[class-name : Main], [caller-function : main], [ line-no : 8], printing log in main