Output Spark application id in the logs with Log4j Output Spark application id in the logs with Log4j json json

Output Spark application id in the logs with Log4j


I doubt that org.apache.hadoop.log.Log4Json can be adjusted for this purpose. According to its javadoc and source code it might be rather cumbersome.

Although it looks like you are using Log4j 1x, its API is quite flexible and we can easily define our own layout by extending org.apache.log4j.Layout.

We'll need a case class that will be transformed into JSON according to the target structure:

case class LoggedMessage(name: String,                         appId: String,                         thread: String,                         time: Long,                         level: String,                         message: String)

And Layout might be extended as follows. To access the value of "app_id", we'll use Log4j's Mapped Diagnostic Context

import org.apache.log4j.Layoutimport org.apache.log4j.spi.LoggingEventimport org.json4s.DefaultFormatsimport org.json4s.native.Serialization.writeclass JsonLoggingLayout extends Layout {  // required by the API  override def ignoresThrowable(): Boolean = false  // required by the API  override def activateOptions(): Unit = { /* nothing */ }  override def format(event: LoggingEvent): String = {    // we are using json4s for JSON serialization    implicit val formats = DefaultFormats    // retrieve app_id from Mapped Diagnostic Context    val appId = event.getMDC("app_id") match {      case null => "[no_app]" // logged messages outside our app      case defined: AnyRef => defined.toString    }    val message = LoggedMessage("TODO",                                appId,                                Thread.currentThread().getName,                                event.getTimeStamp,                                event.getLevel.toString,                                event.getMessage.toString)    write(message) + "\n"  }}

Finally, when the Spark session is created, we put the app_id value into MDC:

import org.apache.log4j.{Logger, MDC}// create Spark sessionMDC.put("app_id", session.sparkContext.applicationId)logger.info("-------- this is info --------")logger.warn("-------- THIS IS A WARNING --------")logger.error("-------- !!! ERROR !!! --------")

This produces following logs:

{"name":"TODO","appId":"local-1550247707920","thread":"main","time":1550247708149,"level":"INFO","message":"-------- this is info --------"}{"name":"TODO","appId":"local-1550247707920","thread":"main","time":1550247708150,"level":"WARN","message":"-------- THIS IS A WARNING --------"}{"name":"TODO","appId":"local-1550247707920","thread":"main","time":1550247708150,"level":"ERROR","message":"-------- !!! ERROR !!! --------"}

And, of course, do not forget to refer the implementation in log4j config xml:

<appender name="Json" class="org.apache.log4j.ConsoleAppender">  <layout class="stackoverflow.q54706582.JsonLoggingLayout" /></appender>