I have a basic Groovy script, and I'm looking to create logs as simply as possible. I want the message to go to stdout, as well as a log file, and each entry in the log file would have a timestamp.
I can't use the @Log notation, because it's a script, and I don't have a class to inject into. This would have been ideal otherwise I think.
A debug log can record database operations, system processes, and errors that occur when executing a transaction or running unit tests. Debug logs can contain information about: Database changes.
Groovy is a scripting language with Java-like syntax for the Java platform. The Groovy scripting language simplifies the authoring of code by employing dot-separated notation, yet still supporting syntax to manipulate collections, Strings, and JavaBeans.
You can have the below pattern in your script (tried in Groovy Editor).
import java.util.logging.Logger Logger logger = Logger.getLogger("") logger.info ("I am a test info log")
The above logs output to STDOUT. In order to log it to a file, you have to create a logger using getLogger
. Follow the API for your convenience.
Using Log annotation is the simplest way to enable logging in groovy. Combine this with a Grape annotation to pull down the logging framework and you have everything you need in one script:
// // Dependencies // ============ import groovy.util.logging.Slf4j @Grapes([ @Grab(group='ch.qos.logback', module='logback-classic', version='1.0.13') ]) // // Classes // ======= @Slf4j class StandardGreeting { def greet() { log.trace "Hello world" log.debug "Hello world" log.warn "Hello world" log.info "Hello world" log.error "Hello world" } } @Slf4j class SpecialGreeting { def greet() { log.trace "Hello world" log.debug "Hello world" log.warn "Hello world" log.info "Hello world" log.error "Hello world" } } @Slf4j class GreetingRunner { def greetings = [new StandardGreeting(), new SpecialGreeting()] def run() { log.info "Starting to talk" greetings.each { it.greet() } log.info "Finished talking" } } // // Main program // ============ def runner = new GreetingRunner() runner.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With