简体   繁体   中英

How to use configuration file with groovy annotation @Log4j

I have a groovy script called "xxx" added to the PATH so I can use it avoiding "groovy xxx". This script loads dynamcally other classes. I would like to use the @Log4j annotation in those classes and configure log4j with properties file in a folder /home/user/test/log4j.properties but I'm not able to understand how it works exactly.

the script code is:

System.setProperty("log4j.debug", "true")
System.setProperty("log4j.configuration", "/home/user/test/log4j.properties")

def s = new File("/home/user/test/log4j.properties").toURL()
this.class.classLoader.addURL(s)
println "started: ${this.class.classLoader}"
// other code

when I execute the command "xxx", the output is:

$ xxx
started: groovy.lang.GroovyClassLoader$InnerLoader@1ac91010
log4j: Trying to find [/home/user/test/log4j.properties] using context classloader groovy.lang.GroovyClassLoader@4ccdd309.
log4j: Trying to find [/home/user/test/log4j.properties] using groovy.lang.GroovyClassLoader@4ccdd309 class loader.
log4j: Trying to find [/home/user/test/log4j.properties] using ClassLoader.getSystemResource().
log4j: Could not find resource: [/home/user/test/log4j.properties].
..log4j:WARN No appenders could be found for logger (groovy.Datastore).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

The classloader is not the same and the file can't be found. How exactly this procedure works? is there a way to NOT use:

groovy -cp /home/user/test/log4j.properties -Dlog4j.configuration=/home/user/test/log4j.properties xxx

UPDATE I've figured out that the classloader used is the context classLoader reachable with Thread.currentThread().getContextClassLoader(). The problem now is that I'm not able to set the property file in the classpath but a workaround is to put it into a jar and place it in the groovy lib folder. Is there an easy way to load a property file in the context class loader?

Presumably, you are trying to configure Log4j with all of this. Class loaders are for loading classes. Property files are not class files. This means that the easiest way to do this is not to do it at all.

Instead, you might want to peruse the Log4j documentation and see how they do not use class loaders to configure (if that is what you are trying to do) Log4j.

Simply open the property file in the usual way and use the appropriate methods mentioned in the Log4j documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM