Reputation: 2555
I'm trying to configure Grails so as to use external Log4j2 configuration files separating production and development mode. It should listen for configuration changes and refresh it after some period of time.
For Grails 2.x, it can be done by registering Log4jConfigurer
beans like this:
switch (Environment.current) {
case Environment.PRODUCTION:
log4jConfigurer(MethodInvokingFactoryBean) {
targetClass = "org.springframework.util.Log4jConfigurer"
targetMethod = "initLogging"
arguments = ["classpath:ogc-log4j.xml", 30000]
}
case Environment.DEVELOPMENT:
log4jConfigurer(MethodInvokingFactoryBean) {
targetClass = "org.springframework.util.Log4jConfigurer"
targetMethod = "initLogging"
arguments = ["classpath:log4j-dev.xml", 30000]
}
}
For some reasons, this approach doesn't work in Grails 3.x. How can I do this in Grails 3.3.3 or in Spring Boot (I guess it should work because Grails 3.x is based on Spring Boot)?
Upvotes: 0
Views: 572
Reputation: 1671
I reckon we can achieve the desired need with different approaches. As far as I have been aware of externalising Log4j2
configuration file in Grails 3, we could use either LogerContext
or System.setProperty
. The latter could be done as instructed in the post. My suggestion, as well as the demonstration for this question, is to use LogerContext
as described in Logging Separation section of Log4j2 manual.
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.LoggerContext
class BootStrap {
def init = { servletContext ->
LoggerContext context = (LoggerContext) LogManager.getContext(false)
String userHome = System.getProperty("user.home")
String pathname = ""
if (grails.util.Environment.isDevelopmentMode()) {
pathname = userHome + "/.myConfigurations/log4j2-dev.xml"
} else {
pathname = userHome + "/.myConfigurations/log4j2-prod.xml"
}
File file = new File(pathname)
// this will force a reconfiguration
context.setConfigLocation(file.toURI())
}
}
Please take a look at my project uploaded to Bitbucket. In this project, I tried to log a message after starting the application. The log.info
was called in Application.groovy
. Start the application within grails 3.3.9, you will have to run run-app
to test development or prod run-app
to test production mode.
Upvotes: 0
Reputation: 672
From 3.3.3 of grails
Instead of having it in Java code. Environment configuration has moved to the YML configuration file.
we can pass different values to different environments and change configuration of log4j
refer to the documentation
documentaion for Enviroment configuration
Upvotes: 1