如何使用 kotlin.logging 记录堆栈跟踪?

D.B*_*D.B 6 exception kotlin spring-boot

我使用 kotlin.logging 作为应用程序的日志记录框架。

我希望能够以更易读的方式(可能是 JSON 格式)记录堆栈跟踪:

我正在执行以下操作,但会导致非常冗长/不可读的格式:

logger.error("Exception caught in handleIllegalArgumentsException: $e", e.printStackTrace())
Run Code Online (Sandbox Code Playgroud)

仅记录 Throwable 异常时(见下文),它不显示堆栈跟踪:

logger.error("Exception caught in handleIllegalArgumentsException: $e") 
Run Code Online (Sandbox Code Playgroud)

Ant*_*rte 12

对于通过谷歌搜索到达这里的人:

由于 Kotlin 1.4 Throwable 有一个扩展方法,允许您以字符串形式获取堆栈跟踪,这基本上执行其他答案所建议的操作。


/**
 * Returns the detailed description of this throwable with its stack trace.
 *
 * The detailed description includes:
 * - the short description (see [Throwable.toString]) of this throwable;
 * - the complete stack trace;
 * - detailed descriptions of the exceptions that were [suppressed][suppressedExceptions] in order to deliver this exception;
 * - the detailed description of each throwable in the [Throwable.cause] chain.
 */
@SinceKotlin("1.4")
public actual fun Throwable.stackTraceToString(): String {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    printStackTrace(pw)
    pw.flush()
    return sw.toString()
}
Run Code Online (Sandbox Code Playgroud)

这意味着原来的e.printStackTrace()只需更改为e.stackTraceToString()

就像这样:

logger.error("Exception caught in handleIllegalArgumentsException: ${e.stackTraceToString()}") 
Run Code Online (Sandbox Code Playgroud)


cho*_*hom 6

您应该能够使用以下方式获取堆栈跟踪。

logger.error(e) {"Exception caught in handleIllegalArgumentsException}
Run Code Online (Sandbox Code Playgroud)

  • 缺少收盘价 (3认同)

Мих*_*аль 0

Stacktrace 始终是多行的,而传统的日志记录消息应该是单行的。因此,您需要首先将其保存到String变量中,然后以某种方式替换换行符号(|例如使用符号):

logger.error {
    val stacktrace = StringWriter().also { e.printStackTrace(PrintWriter(it)) }.toString().trim()
    val singleLineStackTrace = stacktrace.lines().map { it.trim() }.joinToString(separator = "|")
    "Exception caught in handleIllegalArgumentsException: $singleLineStackTrace"
}
Run Code Online (Sandbox Code Playgroud)

然后日志将如下所示:

[main] ERROR Logging - Exception caught in handleIllegalArgumentsException: java.lang.IllegalArgumentException: !!!!|at LoggingKt.main(logging.kt:12)|at LoggingKt.main(logging.kt)
Run Code Online (Sandbox Code Playgroud)