Application Insights异常定位显示库层级,如何改为应用代码位置?
解决Application Insights异常栈只显示自定义代码位置的方法
方法一:通过配置文件过滤栈跟踪
直接在Spring Boot的配置文件(application.yml或application.properties)中添加规则,让Application Insights只保留你应用包下的栈帧,排除第三方库:
YAML配置示例
azure.application-insights: instrumentation: exceptions: stack-filter: # 只保留自己应用的包路径 include: "com.example.test.*" # 排除常见第三方库包 exclude: "org.springframework.*,com.microsoft.*,java.*,javax.*"
Properties配置示例
azure.application-insights.instrumentation.exceptions.stack-filter.include=com.example.test.* azure.application-insights.instrumentation.exceptions.stack-filter.exclude=org.springframework.*,com.microsoft.*,java.*,javax.*
配置生效后,Application Insights捕获的异常栈会自动过滤掉第三方库的层级,优先显示你自己代码中的调用位置。
方法二:自定义异常上报逻辑
如果配置文件的过滤规则不够灵活,可手动实现异常栈过滤后再上报:
- 创建自定义异常上报组件
@Component public class AppExceptionReporter { private final TelemetryClient telemetryClient; public AppExceptionReporter(TelemetryClient telemetryClient) { this.telemetryClient = telemetryClient; } public void reportException(Exception ex) { // 过滤栈帧,仅保留应用包下的内容 StackTraceElement[] filteredFrames = Arrays.stream(ex.getStackTrace()) .filter(frame -> frame.getClassName().startsWith("com.example.test.")) .toArray(StackTraceElement[]::new); // 替换原异常的栈跟踪 ex.setStackTrace(filteredFrames); // 上报到Application Insights telemetryClient.trackException(new ExceptionTelemetry(ex)); } }
- 在全局异常处理器中使用
@ControllerAdvice public class GlobalExceptionHandler { private final AppExceptionReporter exceptionReporter; public GlobalExceptionHandler(AppExceptionReporter exceptionReporter) { this.exceptionReporter = exceptionReporter; } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResult> handleAllExceptions(Exception ex) { // 上报过滤后的异常 exceptionReporter.reportException(ex); // 构建前端响应 ErrorResult result = new ErrorResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } }
注意事项
- 确保配置的
include包路径与你的实际应用代码包完全匹配,避免漏过滤或误过滤。 - 若使用较旧版本的Application Insights SDK,配置项可能略有差异,建议使用最新稳定版SDK。
内容的提问来源于stack exchange,提问作者ilhan
相关产品推荐
相关产品推荐

