Search code examples
javavariablesgroovylogbacklogback-groovy

Variable Substitution in logback groovy


I was working with the logback.xml and the variable were load in string like :

<FileNamePattern>${logDirectory}/${logFileName}.%d{yyyy-MM-dd}.%i.html</FileNamePattern>

where logDirectory and logFileName were set in .bat file before calling my jar.

set logFileName=foobar

But now, I deal with groovy. It's awesome and ridiculously more readable than xml. But the variable are no longer expand.

appender("FILE", RollingFileAppender) {
file = "${logDirectory}/${logFileName}.html"
    rollingPolicy(TimeBasedRollingPolicy) {
        fileNamePattern = "${logDirectory}/${logFileName}.%d{yyyy-MM-dd}.%i.html"
        ...
    }
...
} 

The path is now null/null :'(

WORST : the following test throw an exception :

if ("${logConsole}" == "true") {

Anyone see how to make it work ?

-- EDIT add the full logback.groovy

/*
 * The configuration use the following variables :
 * logDirectory => The log folder
 * logFileName => The log file name
 * logConsole => true console activation.
 **/

import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.html.HTMLLayout
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.encoder.LayoutWrappingEncoder
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy

import static ch.qos.logback.classic.Level.INFO
import static ch.qos.logback.classic.Level.OFF

def LOG_DIRECTORY = System.getProperty("logDirectory")
def LOG_FILE_NAME = System.getProperty("logFileName")
def LOG_CONSOLE = System.getProperty("logConsole")

appender("FILE", RollingFileAppender) {
    file = "${LOG_DIRECTORY}/${LOG_FILE_NAME}.html"
    rollingPolicy(TimeBasedRollingPolicy) {
        fileNamePattern = "${LOG_DIRECTORY}/${LOG_FILE_NAME}.%d{yyyy-MM-dd}.%i.html"
        timeBasedFileNamingAndTriggeringPolicy(SizeAndTimeBasedFNATP) {
            maxFileSize = "100MB"
        }
        maxHistory = 5
    }
    encoder(LayoutWrappingEncoder) {
        layout(HTMLLayout) {
            pattern = "%level%date%logger{36}%msg"
        }
    }
}
appender("STDOUT", ConsoleAppender) {
    withJansi = true
    encoder(PatternLayoutEncoder) {
        pattern = "%d{HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n"
    }
}
logger("org", INFO)
logger("net", INFO)
logger("freemarker", INFO)

// We don't care about the bean creation at least it's more than a warn
logger("org.springframework.beans.factory", WARN)

root(OFF, ["FILE"])

if (LOG_CONSOLE == "true") {
    root(OFF, ["FILE","STDOUT"]);
}

Solution

  • The System.getProperty() call retrieves properties set with -D on the java command line whereas in the .bat file you are setting shell/environment variables.

    Try using System.getenv() in the logback.groovy file.