Logback Reference + Examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Custom properties (scala example)

Say you want to define a property called "env" to indicate whether the application logs are coming from a beta or production environment.

First you need to create a class that implements ch.qos.logback.core.spi.PropertyDefiner and define a method called getPropertyValue.

package path.to.my.package

import ch.qos.logback.core.Context
import ch.qos.logback.core.spi.PropertyDefiner
import ch.qos.logback.core.status.Status

class EnvPropertyDefiner extends PropertyDefiner{

  // define some expression to indicate whether this app is beta or production
  override def getPropertyValue: String = {
    if (<insert expression>) "beta" else "production"

  // these other methods are needed to implement the interface but they aren't 
  // really needed right now
  override def addInfo(msg: String): Unit = ()

  override def addInfo(msg: String, ex: Throwable): Unit = ()

  override def addWarn(msg: String): Unit = ()

  override def addWarn(msg: String, ex: Throwable): Unit = ()

  override def addError(msg: String): Unit = ()

  override def addError(msg: String, ex: Throwable): Unit = ()

  override def addStatus(status: Status): Unit = ()

  override def getContext: Context = null

  override def setContext(context: Context): Unit = ()

Now you need to declare this property in your logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>

    <define name="env" class="path.to.my.package.EnvPropertyDefiner">

    <!-- other configs omitted -->

After you've defined it as above, you can access the value of your property anywhere in the configuration file via ${env}:

<?xml version="1.0" encoding="UTF-8"?>

    <define name="env" class="path.to.my.package.EnvPropertyDefiner">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <!-- including the environment in the log message -->
            <pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} ${env} %msg%n</pattern>

    <!-- other configs omitted -->

Save logs on elasticsearch

Dialogue & Discussion