Logging in Groovy Script

groovy console log
jenkins groovy log
groovy print
jenkins groovy log to console
groovy log a variable
openam logs
groovy lombok slf4j
groovy math log

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.

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.

Logging in Groovy Script, Instead of jumping right into the basic logging example, we'll start with a basic overview of the Groovy language. Despite Groovy not being an  The Logging#1 contains the Text that was printed as a String in the Groovy Script. As mentioned previously, while we have hard coded this in our example to a constant string, this can also be any of the Message Headers, Message Payload and Message Properties as required.

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()

Getting Started Quickly With Groovy Logging, This local transform adds a logging ability to your program using java.util.logging. Every method call on a unbound variable named log will be mapped to a call  To use Groovy script debugging you need a SoapUI Pro license. You can debug scripts only in the SoapUI Groovy Script test step. Debugging of event handler scripts, setup, teardown and report scripts, Script assertions, data source and data sink scripts, and virtual service scripts is not supported. You can debug only Groovy scripts.

Here's my attempt at creating a minimal example for several logback features including logging to a file. Extending @Mark O'Connor's answer above

foo.groovy:

import groovy.util.logging.Slf4j

@Grab('ch.qos.logback:logback-classic:1.2.1') 

@Slf4j
class Foo {
    @Slf4j
    static class Bar {
        def bar() {
            assert log.name == 'Foo$Bar'
            assert log.class == ch.qos.logback.classic.Logger
            log.trace "bar"
            log.debug "bar"
            log.warn  "bar"
            log.info  "bar"
            log.error "bar"
        }
    }

    def foo() {
        assert log.name == "Foo"
        assert log.class == ch.qos.logback.classic.Logger
        log.trace "foo"
        log.debug "foo"
        log.warn  "foo"
        log.info  "foo"
        log.error "foo"
    }
}

@Slf4j
class Baz {
    def baz() {
        log.name = 'Baz'
        assert log.name == 'Baz'
        assert log.class == ch.qos.logback.classic.Logger
        log.trace "baz"
        log.debug "baz"
        log.warn  "baz"
        log.info  "baz"
        log.error "baz"
    }
}

new Foo().foo()
new Foo.Bar().bar()
new Baz().baz()

logback-test.xml or logback.xml:

<configuration debug="true"> <!-- debug attr enables status data dump -->

   <timestamp key="sec" datePattern="yyyyMMdd_HHmmss"/>

   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
      <encoder>
         <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <!-- see Chapter 6 Layouts for format specifiers -->
      </encoder>
   </appender>

   <!-- for RollingFileAppender see Chapter 3 Appenders -->
   <appender name="FILE" class="ch.qos.logback.core.FileAppender">
      <file>foo_${sec}.log</file>
      <append>true</append> <!-- true is the default for append -->
      <immediateFlush>true</immediateFlush> <!-- true is the default for immediateFlush -->
      <encoder>
         <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </encoder>
   </appender>

   <!-- TRACE < DEBUG < INFO <  WARN < ERROR -->
   <!-- Read Chapter 2 Architecture of logback doc for effective
      level (level inheritance) and accumulation (appender additivity) -->
   <root level="debug">
      <appender-ref ref="STDOUT"/>
   </root>

   <logger name="Foo" level="trace" additivity="true">
      <appender-ref ref="FILE"/>
   </logger>

   <!-- if a logger isn't specified for a name, its level="null" and additivity="true", "null" being synonymous to "inherited" -->

   <!-- '$' acts as '.' it seems -->
   <logger name="Foo$Bar" level="inherited" additivity="true"/> <!-- if additivity false, no appender, otherwise, STDOUT and FILE -->

</configuration>

See logback documentation also

Log (groovy 3.0.3 API), Its Groovydoc states the following regarding use of @Log to inject the The next Groovy code listing shows a script that makes use of these  If you need to use a simple logging in your Groovy script you can use some existing and supported frameworks. Sometimes you do not want or cannot use any other dependencies in your script, so you can write your own simple logger using methodMissing implementation: Supported log levels are TRACE, DEBUG, INFO, WARN and ERROR (otherwise an […]

Using the @Slf4j annotation necessitates two lines of code: the import statement and the annotation itself. Here, in two lines, is how you get a logger in a Groovy script:

import org.slf4j.LoggerFactory

def logger = LoggerFactory.getLogger(this.class)

// Use sl4j's placeholders.
logger.info "Reading entries in {}", tsv
// Use a GString.
logger.debug "Extracted file $outputFile exists"

Easy Groovy Logger Injection and Log Guarding, If you need to use a simple logging in your Groovy script you can use some existing and supported frameworks. Sometimes you do not want or  The script relies on the following parameters: logTitle: the header of the log message details; logType: the type of input message we present to the logging script; ErrorMessage: parameter which holds the exception message when used in exception sub-processes; Message formats. A switch statement is used to format the message based on the given type. The following message types are supported:

Simple Groovy Logger Without Any Logging Framework, Solved: How can i access the logger from a groovy script? Currently we use stdout (System.out.println("a log message")) in our groovy. Initially I thought 'log.info' would make it, which is the println equivalent when working with sopaui groovy script. But since I'm trying to write a log from a class, the class doesn't know 'log.info' by default, that's why I specified the use of 'log4j.Logger', but still not sure what I am missing.

Solved: how to handle logging in groovy scripts, Solved: Hi I''ve developed a number of EPI groovy scripts and have configured logging using private static Log s_log which is logging to the - 223796. Groovy classes and scripts are usually stored in .groovy files. Scripts contain Groovy statements without any class declaration. Scripts can also contain method definitions outside of class definitions. It can be compiled and fully integrated with traditional Java application. Language level support for maps, lists, regular expressions.

Solved: Groovy Script Logging to seperate file, The example file where a Groovy class gets annotated with Slf4j. import groovy.​util.logging.Slf4j // Use annotation to inject log field into the  All scripts have access to a number of situation-specific variables, always including a log object for logging to the Groovy Log and a context object for perform context-specific PropertyExpansions or property handling if applicable. A context-specific variable is always available for directly accessing the SoapUI object model. 1.

Comments
  • This wouldn't work with the script that doesn't have a class defined which is what I think Steve is implying.
  • @RomanGoyenko Fair enough, but scripts can be structured using classes too. The logging annotation is very nifty!