Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in Groovy Script

Tags:

logging

groovy

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.

like image 419
Steve Avatar asked Apr 12 '13 21:04

Steve


People also ask

What is logging in debugging?

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.

What is groovy script used for?

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.


2 Answers

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.

like image 147
dmahapatro Avatar answered Sep 25 '22 06:09

dmahapatro


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() 
like image 22
Mark O'Connor Avatar answered Sep 25 '22 06:09

Mark O'Connor