1

I'm trying to get a Hello World app working with groovy/log4j/ubuntu (working with Groovy 1.7.10). By default, I get no output to the console:

  • Created ~/.groovy/lib, and downloaded the latest log4j jar into there.
  • Created a.groovy:

cat a.groovy:

#! /usr/bin/groovy
import org.apache.log4j.Logger
def log = Logger.getLogger(getClass())

println "Log starting"
log.info("This is Info")
log.error("This is error")
println "Log finished"

Gave it permissions and ran it, and got:

Log starting
Log finished

Shouldn't the default config created a console appender and output to console?

As per this answer, I tried adding a call to org.apache.log4j.BasicConfigurator.configure();, but that didn't change anything.

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905

2 Answers2

4

You need to set the Level so that it displays INFO messages...

Try this:

#! /usr/bin/groovy

// Grab Log4j
@Grab( 'log4j:log4j:1.2.16' )
import org.apache.log4j.Level
import org.apache.log4j.Logger

def log = Logger.getLogger( getClass() )

Logger.rootLogger.level = Level.INFO

println "Log starting"
log.info "This is Info"
log.error "This is error"
println "Log finished"

There's a blog post here I found that shows programatically setting up Log4j

Or, as sreejith says, add a log4j properties file to your classpath (or load it in)

To change the default root appender, you can do:

@Grab( 'log4j:log4j:1.2.16' )
import org.apache.log4j.Level
import org.apache.log4j.ConsoleAppender
import org.apache.log4j.PatternLayout
import org.apache.log4j.Logger
def log = Logger.getLogger(getClass())

Logger.rootLogger.with {
  level = Level.INFO
  removeAllAppenders()
  addAppender( new ConsoleAppender( new PatternLayout( '%d %-5p [%t]: %m%n' ) ) )
}

println "Log starting"
log.info "This is Info"
log.error "This is error"
println "Log finished"

To print:

2012-05-21 11:48:48,225 INFO  [Thread-29]: This is Info

The different pattern symbols can be found here

Community
  • 1
  • 1
tim_yates
  • 167,322
  • 27
  • 342
  • 338
1

Try creating a file with the following contents

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n

and add it to the classpath of the project.

srjit
  • 526
  • 11
  • 25