Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log stack trace using kotlin.logging?

I am using kotlin.logging as my logging framework for an application.

I would like to be able to log the stack trace in a much more readable way (maybe JSON format):

I am doing the following, but it results in a very verbose/unreadable format:

logger.error("Exception caught in handleIllegalArgumentsException: $e", e.printStackTrace())

when logging the Throwable exception only (see below), it does not show the stack trace:

logger.error("Exception caught in handleIllegalArgumentsException: $e") 
like image 230
D.B Avatar asked Oct 24 '20 04:10

D.B


People also ask

Should stack trace be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.

How do I print kotlin stack trace?

In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer.

How do I print a stack trace log file?

To print a stack trace to log you Should declare logger and method info(e. toString()) or log(Level.INFO, e. toString()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages.

Why Kotlin for troubleshooting via application logs?

These approaches make troubleshooting via application logs so much easier for our team members. The code is in Kotlin, but the same principles can easily be transferred to other JVM languages. 1. Only Our Code Thanks to Kotlin’s treatment of exceptions, we get to pick where to catch any exception.

How can I get a class-specific logger instance in Kotlin?

As a result, our Kotlin components can get a class-specific logger instance with this common line of code: private companion object { val log = logger() } … which we think is neat. 22  22 1 More from Mindful Technology

How to print a stack trace to log in Java?

To print a stack trace to log you Should declare logger and method info (e.toString ()) or log (Level.INFO, e.toString ()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages. The java.util.logging package provides the logging capabilities via the Logger class.

How does logcat work on Android?

By default, logcat shows the log output related to the most recently run app only. When an app throws an exception, logcat shows a message followed by the associated stack trace containing links to the line of code. As of Android Studio 2.2, the Run window also displays log messages for the current running app.


3 Answers

You should be able to get stack trace using the following way.

logger.error(e) {"Exception caught in handleIllegalArgumentsException}
like image 116
chom Avatar answered Oct 24 '22 10:10

chom


For the people getting here through a google search:

Since Kotlin 1.4 Throwable has an extension method that allows you to get the Stack Trace as a String, which basically does what is suggested by other answers.


/**
 * 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()
}

This means the original e.printStackTrace() just needs to be changed into e.stackTraceToString()

Like so:

logger.error("Exception caught in handleIllegalArgumentsException: ${e.stackTraceToString()}") 
like image 32
Antero Duarte Avatar answered Oct 24 '22 09:10

Antero Duarte


If you want the logger to print the exception stacktrace:

try {
    ...
} catch (e: Exception) {
    logger.error("Exception caught:", e)
}

If you want the string itself (for further manipulation), you can use what @Михаил Нафталь suggested:

try {
    ...
} catch (e: Exception) {
    val stacktrace = StringWriter().also { e.printStackTrace(PrintWriter(it)) }.toString().trim()
    logger.error("Exception caught: $stacktrace")
}

Both these methods will print the whole stacktrace in the logs, for example:

16:41:50.528 [main] ERROR org.myorg.MyClass - Exception caught:
java.lang.IllegalArgumentException: Argument X was not allowed.
    at org.myorg.MyClass.func (MyClass.kt:124)
    at java.base/java.lang.Thread.run(Thread.java:834)
    etc...

I know it's not answering to what is asked in the question text, but it's answering to the question title. As this post was the first suggestion I got when googling how to log stacktraces with Kotlin, I thought this might help others.

like image 1
jinnlao Avatar answered Oct 24 '22 08:10

jinnlao