In this tutorial, we are going to set up the SiftingAppender in our Gradle Groovy project.
Sifting Appender is useful when we want to separate the log files during runtime i.e if we want to separate the log files per thread or per user session basis.
Unfortunately, in the Gradle Groovy project, SiftingAppender is no longer supported since version 1.0.12 as mentioned in Groovy Configuration.
Let's look into the simple example where we are going to configure the SiftingAppender in logback.groovy, where we want to configure the per-user logging mechanism.
import ch.qos.logback.classic.PatternLayout
import ch.qos.logback.classic.sift.MDCBasedDiscriminator
import ch.qos.logback.classic.sift.SiftingAppender
appender("USER_ROLLING", SiftingAppender) {
discriminator(MDCBasedDiscriminator) {
key = 'userid'
defaultValue = 'NONE'
}
sift {
appender("FILE-${userid}", FileAppender) {
file = "Path-to-log/${userid}.log"
append = true
layout(PatternLayout) {
pattern = "%level %logger - %msg%n"
}
}
}
}
logger("package-to-log",TRACE,['USER_ROLLING'], false)
This is a simple example SiftingAppender configuration; this is derived from logback sifting appender xml configuration.
We are using the Mapped Diagnostic Context for mapping the context user to create a separate file. We can do a similar for the thread as well.
Let's set up the MDC for user, the sample example looks as below.
import groovy.util.logging.Slf4j
import org.slf4j.MDC
@Slf4j
class UserLogging {
public static void debug(String message, String userid = '') {
setUserMDC(userid)
log.debug(message)
}
public static void error(String message, String userid = '') {
setUserMDC(userid)
log.error(message)
}
public static void info(String message, String userid = '') {
setUserMDC(userid)
log.info(message)
}
public static void setUserMDC(String userid) {
try {
if (!userid) {
MDC.remove("userid")
return
}
MDC.put("userid", userid)
}catch(e) {
log.error("Error setting user Mapped Diagnostic Context due to "+e.getMessage())
}
}
}
Here, if the userid is available then we are setting the MDC for userid so the log file can be written in a separate file per user. If you want to do with request user do the similar in filter class or the place where it suits.
Now, if we run the application we will get the error as a result the appender doesn't work. So, here we found the solution project that extends Logback Gaffer so that SiftingAppender can be configured in Groovy DSL from this Github repo.
Simply download the jar file for that project and add it to the application.
For the Gradle project create a libs directory under the project directory and load and compile from build.gradle file.
Under build.gradle under dependencies{} section:
compile fileTree(dir: 'libs', include: '*.jar')
If we run the application it suppose to work. The log file will be created on the respective file path.