Scala: print a stack trace in my Scalatra app

后端 未结 4 1392
萌比男神i
萌比男神i 2021-02-13 18:02

Seems like a fairly straight forward problem, but I\'d like to log a stack trace when my top level error handler in Scalatra is triggered. I\'m intentionally throwing an excepti

相关标签:
4条回答
  • 2021-02-13 18:39

    This question has several ways to convert an exception stack trace to a String. printStackTrace outputs to System.err unless you provide a writer.

    0 讨论(0)
  • 2021-02-13 18:42

    If you use the standard logger: com.typesafe.scalalogging.Logger , the logger prints the stack trace for you.

    You can just use it this way:

    import com.typesafe.scalalogging.Logger
    import org.slf4j.LoggerFactory
    
    try {     
        throw new Exception("test message")
    } catch {
        case e:Exception => logger.error("Exception " , e)
    }
    

    There is already an overload which is accepting 2 parameters, String and Throwable.

    0 讨论(0)
  • 2021-02-13 18:50

    I think you want printStackTrace() rather than getStackTrace. If you are outputting to a log file, getMessage() may be helpful. Or you may try passing the whole exception object to the logger.

    0 讨论(0)
  • 2021-02-13 18:52

    Use ExceptionUtils from Apache Commons Lang:

    import org.apache.commons.lang3.exception.ExceptionUtils
    (...)
    logger.info("an exception occurred: " + ExceptionUtils.getStackTrace(e))
    
    0 讨论(0)
提交回复
热议问题