Java获取自身被调用点
1. 场景
打印日志的时候,需要获取是在哪个地方被调用了,把调用点的信息一并打印出来。
2. 获取自身被调用点的方法
可以通过获取线程的调用栈,遍历后找到调用点。
3. 代码实现
import java.text.SimpleDateFormat;
import java.util.Date;
public class Log {
private static final String INFO = "INFO";
private static final String WARN = "WARN";
private static final String ERROR = "ERROR";
private static final String DEBUG = "DEBUG";
private static final String THREAD_CLASS_NAME = Thread.class.getName();
private static final String SELF_CLASS_NAME = Log.class.getName();
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static StackTraceElement findCallPoint() {
Thread currentThread = Thread.currentThread();
StackTraceElement[] stackTraces = currentThread.getStackTrace();
for (StackTraceElement stackTrace : stackTraces) {
if (THREAD_CLASS_NAME.equals(stackTrace.getClassName()) || SELF_CLASS_NAME.equals(stackTrace.getClassName())) {
continue;
}
return stackTrace;
}
return null;
}
private static String getMsgPrefix(String msgType) {
StackTraceElement callPoint = findCallPoint();
if (callPoint == null) {
return "-";
}
return String.format("%s %s --- %s(%d) \t%s()\t", DATE_FORMAT.format(new Date()), msgType,
callPoint.getClassName(), callPoint.getLineNumber(), callPoint.getMethodName());
}
public static void info(String msg) {
System.out.println(getMsgPrefix(INFO) + msg);
}
public static void warn(String msg) {
System.out.println(getMsgPrefix(WARN) + msg);
}
public static void error(String msg) {
System.out.println(getMsgPrefix(ERROR) + msg);
}
public static void debug(String msg) {
System.out.println(getMsgPrefix(DEBUG) + msg);
}
}
4. 测试
测试代码:
package com.example.study.controller;
public class Test {
public static void main(String[] args) {
Log.info("=====testLog main=====");
testLog();
}
private static void testLog() {
Log.info("=====testLog info=====");
Log.warn("=====testLog warn=====");
Log.error("=====testLog error=====");
Log.debug("=====testLog debug=====");
}
}
控制台输出:
2024-12-26 23:18:35.313 INFO --- com.example.study.controller.Test(7) main() =====testLog main=====
2024-12-26 23:18:35.315 INFO --- com.example.study.controller.Test(12) testLog() =====testLog info=====
2024-12-26 23:18:35.315 WARN --- com.example.study.controller.Test(13) testLog() =====testLog warn=====
2024-12-26 23:18:35.315 ERROR --- com.example.study.controller.Test(14) testLog() =====testLog error=====
2024-12-26 23:18:35.315 DEBUG --- com.example.study.controller.Test(15) testLog() =====testLog debug=====