Multiple markers in logback pattern layout

2.4k Views Asked by At

I'm currently playing around with Logback/Markers and I haven't found a way to format the output of markers. Because of the issues with MDC in combination with Play I'd like to misuse Markers to print username, correlationId and host with every log statement.

I'm setting two markers, "host" and "user" in my example

trait RequestMarkerContext {
  implicit def requestHeaderToMarkerContext(implicit request: RequestHeader): MarkerContext = {
    import net.logstash.logback.marker.Markers._

    val markers: java.util.Map[String, String] = new util.HashMap()
    markers.put("user", "testuser")
    markers.put("host", "somehost")

    val value: LogstashMarker = appendEntries(markers)
    MarkerContext(value)
  }
}

And when I add them to the layout of my appender.

<layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} [%level] %logger - %marker %msg%n</Pattern>
</layout>

they are printed in JSON format like this:

2018-09-07T15:16:45.462+0200 [warn] controllers.HomeController - {host=somehost, user=testuser} ...

but I would rather print them like this, because it would fit the rest of the log message:

2018-09-07T15:16:45.462+0200 [warn] controllers.HomeController - host='somehost', user='testuser' ... 

Is there any way to change the layout of markers? I found this comment which says non-JSON output is not and won't be supported.

Does anyone know of any other way to customize the output?

1

There are 1 best solutions below

0
Daniel On

I've just figured out how it works, but it's not super pretty.

implicit def requestHeaderToMarkerContext(implicit request: RequestHeader): MarkerContext = {
    import net.logstash.logback.marker.Markers._

    val username = "john"
    val host = "127.0.0.1"

    val message = s"username='$username', host='$host',"
    val value: LogstashMarker = appendFields(message)

    MarkerContext(value)
}