Skip to content

Instantly share code, notes, and snippets.

@neversleepz
Created November 9, 2013 03:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save neversleepz/7381062 to your computer and use it in GitHub Desktop.
Save neversleepz/7381062 to your computer and use it in GitHub Desktop.
Configuring log4j for use in a groovy script. Reading log4j config (via a config slurper)
log4j {
appender.stdout = "org.apache.log4j.ConsoleAppender"
appender."stdout.layout"="org.apache.log4j.PatternLayout"
appender.scrlog = "org.apache.log4j.FileAppender"
appender."scrlog.layout"="org.apache.log4j.TTCCLayout"
appender."scrlog.file"="script.log"
rootLogger="debug,scrlog,stdout"
/** these don't do nothing but illustrate how to configure logging on packages
logger.org.springframework="info,stdout"
additivity.org.springframework=false
**/
}
/**
* Use log4j in a groovy script, with configuration from a groovy like config file
*
* As asked in this
* <a href="http://stackoverflow.com/questions/19868180/groovy-script-and-log4j">stackoverflow question - groovy-script-and-log4j</a>
*
*
* Tested with Java 7, Groovy 2.1.9
* User: kon
* Date: 9/11/13
* Time: 11:48 AM
*/
@Grab('log4j:log4j:1.2.17')
import org.apache.log4j.*
import groovy.util.logging.*
@Log4j
class HelloWorld{
def execute() {
def config = new ConfigSlurper().parse(new File('log4jconfig.groovy').toURL())
PropertyConfigurator.configure(config.toProperties())
// this will print/write as the loglevel is info
log.debug 'Execute HelloWorld.'
// this will print
log.info 'Simple sample to show log field is injected.'
}
}
def helloWorld = new HelloWorld()
helloWorld.execute()
@hammer2j2
Copy link

Thanks for the example. What is the toURL() method doing in line 21?

@mesameen
Copy link

Thanks,

How to create multiple log files which are like

  1. Detail (ALL level of logs)
  2. Fail (ERROR level of logs)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment