Java-打印业务堆栈-找到调用set操作的堆栈,判断执行的逻辑(分析调用上下文)
示例1:
找到调用set操作的堆栈,判断执行的逻辑(分析调用上下文)
public void setIsCorrect(Boolean o) {
if (o) {
this.isCorrect = 1;
} else {
StackTraceElement[] ss = Thread.currentThread().getStackTrace();
for (StackTraceElement s : ss) {
System.out.println(s);
}
this.isCorrect = 2;
}
示例2:
public static void main(String[] args) {
EduTrainStatService statService = new EduTrainStatService();
String s = statService.get();
List<String> stackTraceElementList = getStackTraceElement();
stackTraceElementList.forEach(System.out::println);
log.info("updateTrainUserStatus更新用户的课程和考试状态入参,调用堆栈:{}",stackTraceElementList);
}
private static List<String> getStackTraceElement(){
StackTraceElement[] ss = Thread.currentThread().getStackTrace();
List<String> st = Lists.newArrayList();
for (StackTraceElement s : ss) {
if(s.toString().contains("edu")){
st.add(s.toString());
}
}
return st;
}
示例3:
只要当前业务堆栈,排查java和Spring堆栈:
log.info("getCourseChapterSection查询课程章节:courseId={},请求来源={}\n", courseId, getRequestSource());
/**
* 获取请求来源和业务代码堆栈
* @return
*/
private String getRequestSource() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StringBuilder lastInvoked = new StringBuilder();
int stackTraceLength = stackTraceElements.length;
//最多只记录3条
int maxRecordLength = 3;
//标记已保存的堆栈条数
int currentRecordLength = 0;
//获取最近的业务堆栈,其他堆栈跳过
for (int i = 1; i < stackTraceLength; i++) {
String se = stackTraceElements[i].toString();
if (currentRecordLength >= maxRecordLength ) {
break;
}
if (se.contains("com.safety51") && !se.contains("$$") && !se.contains("getRequestSource")) { // && !se.contains("$$")
isTargetRecord = true;
lastInvoked.append(stackTraceElements[i].toString());
lastInvoked.append("\n");
currentRecordLength++;
}else{
if(isTargetRecord){
break;
}
}
}
if (lastInvoked.length() < 1 && stackTraceLength >= 4) {
lastInvoked.append(Thread.currentThread().getStackTrace()[2].toString());
lastInvoked.append(Thread.currentThread().getStackTrace()[3].toString());
}
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return "非web请求,调用链:\n" + lastInvoked.toString();
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
return "web请求:"+ request.getRequestURL().toString() + ",调用链:\n" + lastInvoked.toString();
}
搜索日志
在一些方法前面找到一定会执行的sql或代码
正文到此结束
- 本文标签: Spring Boot Spring
- 本文链接: https://code.jiangjiesheng.cn/article/213
- 版权声明: 本文由小江同学原创发布,转载请先联系本站长,谢谢。