Conditional logging with Logback in Scala

Reading Time: < 1 minute

Hello Folks

In my project , i got a scenario where I wanted conditional logging. I was using Logback framework for the same. I wanted to set different logging level for staging and production.

Either i could do manually changes in logback.xml for logging level for staging and production both. But this is not the good practice. Then I found the solution of implementing the conditions in logback.xml itself and that provided me the better and efficient solution.

First, we will see the way of implementing the conditions in logback.xml. There are 2 ways to do the same :

if-then form

if-then-else form

Now we have learnt how to make conditions. Now we will see what conditional expressions we can use in logback.xml.

There are 3 ways to do this :

1. Using property() or p() :

Only context properties or system properties are accessible. For a key passed as argument, the property() or its shorter equivalent p() methods return the String value of the property.

2. Using isDefined() :

It is used to check whether a property is defined or not.

3. Using isNull() :

It is used to check whether a property is null or not.

A full Example to make different logging level for staging and production.

Set the property as : export runMode=prod

Cheers !!!

Written by 

Rishi is a tech enthusiast with having around 10 years of experience who loves to solve complex problems with pure quality. He is a functional programmer and loves to learn new trending technologies. His leadership skill is well prooven and has delivered multiple distributed applications with high scalability and availability by keeping the Reactive principles in mind. He is well versed with Scala, Akka, Akka HTTP, Akka Streams, Java8, Reactive principles, Microservice architecture, Async programming, functional programming, distributed systems, AWS, docker.

1 thought on “Conditional logging with Logback in Scala2 min read

Comments are closed.

%d bloggers like this: