Java 如何只记录异常的一部分?

Java 如何只记录异常的一部分?,java,exception,logging,sonarqube,Java,Exception,Logging,Sonarqube,SonarQube用标记此异常,记录或重新显示此异常。这对我们来说很有意义,因此我们在日志行中添加了e: private static InputStream getFileFromClassPathOrFileSystem(String path) { try { //try to get from something like file:///some/path, and if missing Scheme exception, go to catch clause

SonarQube用
标记此异常,记录或重新显示此异常。这对我们来说很有意义,因此我们在日志行中添加了
e

private static InputStream getFileFromClassPathOrFileSystem(String path) {
    try {
        //try to get from something like file:///some/path, and if missing Scheme exception, go to catch clause
        return Files.newInputStream(Paths.get(URI.create(path)));
    } catch (IllegalArgumentException | IOException e) {
        LOGGER.info("Could not retrieve from file system, trying classpath. If the exception is 'Missing scheme' this can be ignored");
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
    }
}

虽然这解决了声纳问题,确实给了我们更多有用的信息,但我们现在被40行堆栈跟踪淹没了。(该方法称为a LOT,您可以只使用原因消息而不使用完整堆栈:

LOGGER.info("Could not retrieve from file system, trying classpath. If the exception is 'Missing scheme' this can be ignored", e);
返回此可丢弃文件的详细信息字符串


在生产系统中,堆栈跟踪/日志总是要保存的,它们是系统运行时的记录

PS:请检查为什么这个特殊方法会出现这么多异常

如果不想记录,可以将记录器级别更改为debug/trace,这样可以避免减少堆栈跟踪

e.getMessage()
下面是一段代码(从e.printStackTrace()复制而来),它将打印消息和前5行

免责声明:请不要在生产中使用

LOGGER.debug("Could not retrieve from file system, trying classpath. If the exception is 'Missing scheme' this can be ignored", e);
LOGGER.trace("Could not retrieve from file system, trying classpath. If the exception is 'Missing scheme' this can be ignored", e);
StackTraceElement[]ele=e.getStackTrace();
System.out.println(e.getMessage());

对于(int i=0;i可能最好的解决方案是标记SonarQube警告

为了说服记录器只打印stacktrace的“感兴趣的位”,您很可能需要编写一个自定义日志消息格式化程序或附加程序。可靠地确定感兴趣的位是什么(跨越应用程序可能抛出的所有异常等)可能是一个挑战

请注意,记录异常消息(如建议的)不会关闭SonarQube。至少,如果相信此测试用例,则不会:

另一方面,它看起来像:

StackTraceElement[] ele = e.getStackTrace();
System.out.println(e.getMessage());
for(int i=0; i<ele.length && i<=5; i++){
System.out.println("at " + ele[i]);
}

SonarQube可以接受,但它不记录任何stackframes。

LOGGER.info(无法从文件系统中检索,请尝试classpath。如果异常为“缺少scheme”,则可以忽略“{}”,例如.getMessage());这仍将标记为“记录或重新显示此异常”。:'(
} catch (Exception e) { // Compliant
  String message = "Some context for exception" + e.getMessage();
  JAVA_LOGGER.info(message);
}