获取Scala代码报错日志相关信息


前言

在scala程序中,我们有时想搜集报错日志的一些相关内容,如报错内容,报错代码在第几行,为该报错打上报错类型。

使用步骤

1.引入库

代码如下(示例):

import org.json4s.DefaultFormats
import org.json4s.native.Json
import org.apache.commons.lang3.exception.ExceptionUtils

2.自定义报错日志相关信息搜集函数

代码如下(示例):

def getErrorLogMessage(ex: Exception): String ={
    val errorLab = ExceptionUtils.getMessage(ex)
    val errorContent = ExceptionUtils.getRootCauseMessage(ex)
    val errorTraceArr = ExceptionUtils.getRootCauseStackTrace(ex).filter(_.contains(getClass.getSimpleName))
    if (errorTraceArr.isEmpty) {
      null
    } else {
      val errorTrace = errorTraceArr.head.replace("\t","")
      Json(DefaultFormats).write(Map("errorLab" -> errorLab, "errorContent" -> errorContent, "errorTrace" -> errorTrace))
    }
  }

getErrorLogMessage函数中jobObjectName参数是指运行程序中的Object,例子中的jobObjectName为:errorLogAppend。函数的输出是一个Json,errorLab是为该报错打上报错类型,例子中是"errorLab Symbol",errorContent与errorTrace分别是报错内容,报错代码在main函数的第几行

3.main函数

代码如下(示例):

import org.json4s.DefaultFormats
import org.json4s.native.Json
import org.apache.commons.lang3.exception.ExceptionUtils

object errorLogAppend {
  def main(args: Array[String]): Unit = {

    val str = null
    try {
      println(fun1(str))
    }catch {
      case ex: Exception => {
        val errorMessage = getErrorLogMessage(ex)
        println("errorMessage:   "+errorMessage)
      }
    }
  }

  def fun1(str:AnyRef): String ={
    try {
      str.toString
    } catch {
      case ex: Exception => {
        throw AnalysisException("errorLab Symbol", ex)
      }
    }
  }

  @throws[AnalysisException]
  def getErrorLogMessage(ex: Exception): String ={
    val errorLab = ExceptionUtils.getMessage(ex)
    val errorContent = ExceptionUtils.getRootCauseMessage(ex)
    val errorTraceArr = ExceptionUtils.getRootCauseStackTrace(ex).filter(_.contains(getClass.getSimpleName))
    if (errorTraceArr.isEmpty) {
      null
    } else {
      val errorTrace = errorTraceArr.head.replace("\t","")
      Json(DefaultFormats).write(Map("errorLab" -> errorLab, "errorContent" -> errorContent, "errorTrace" -> errorTrace))
    }
  }
}

case class AnalysisException(message:String,cause:Throwable) extends Exception(message:String,cause:Throwable)

main函数运行fun1会产生一个报错,报错会在catch中运行getErrorLogMessage(“errorLogAppend”, ex)搜集起来。


总结

报错代码在第几行的信息为追求最简,只打印了报错所在行的行数,其他报错Trace未打印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值