com.teambytes.cloudwatch.appenders.logback.CloudwatchJsonDataAppender.scala Maven / Gradle / Ivy
The newest version!
package com.teambytes.cloudwatch.appenders.logback
import ch.qos.logback.classic.spi.{IThrowableProxy, ILoggingEvent}
import com.fasterxml.jackson.databind.{SerializationFeature, ObjectMapper}
import scala.collection.JavaConverters._
class CloudwatchJsonDataAppender extends CloudwatchAppender {
private val om = {
val omap = new ObjectMapper()
omap.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
omap
}
def append(event: ILoggingEvent): Unit = {
try {
sendEvent(om.writeValueAsString(iLoggingEvent2Map(event)))
} catch {
case e: Exception =>
e.printStackTrace()
addError("Error while sending a message", e);
}
}
private def iLoggingEvent2Map(event: ILoggingEvent) = {
val callerData = if (event.hasCallerData) { Some(event.getCallerData) } else { None }
val markers = Option(event.getMarker).map(_.iterator().asScala.map(_.toString).toSet)
Map(
"threadName" -> event.getThreadName,
"level" -> event.getLevel,
"message" -> event.getMessage,
"argumentArray" -> event.getArgumentArray,
"formattedMessage" -> event.getFormattedMessage,
"loggerName" -> event.getLoggerName,
"loggerContextVO" -> event.getLoggerContextVO,
"throwableProxy" -> getThrowableProxyMap(Option(event.getThrowableProxy)),
"markers" -> markers,
"mdcPropertyMap" -> event.getMDCPropertyMap,
"timeStamp" -> event.getTimeStamp
) ++ callerData.map(cd => Map("callerData" -> cd))
}
private def getThrowableProxyMap(throwableProxyOpt: Option[IThrowableProxy]): Map[String, Any] = {
throwableProxyOpt.map { throwableProxy => Map(
"message" -> throwableProxy.getMessage,
"className" -> throwableProxy.getClassName,
"stackTraceElements" -> throwableProxy.getStackTraceElementProxyArray,
"commonFrames" -> throwableProxy.getCommonFrames,
"cause" -> getThrowableProxyMap(Option(throwableProxy.getCause)),
"suppressed" -> throwableProxy.getSuppressed
)}.getOrElse(Map.empty[String, Any])
}
}