Logging in Groovy

Here’s the translation of the Go logging example to Groovy, formatted in Markdown suitable for Hugo:

Our first example demonstrates logging in Groovy. The standard library provides straightforward tools for outputting logs from Groovy programs.

import groovy.util.logging.Log
import groovy.util.logging.Slf4j

@Log
class StandardLogger {
    static void main(String[] args) {
        // Simply invoking methods like 'info' from the @Log annotation
        // uses the standard logger, which is already pre-configured for
        // reasonable logging output.
        log.info("standard logger")

        // Loggers can be configured with patterns to set their output format.
        // This is typically done in a configuration file, but can also be
        // set programmatically.
        System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug")
        System.setProperty("org.slf4j.simpleLogger.showDateTime", "true")
        System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss:SSS")

        log.info("with date and time")

        // It's common in Groovy to use the @Slf4j annotation for more
        // advanced logging capabilities.
    }
}

@Slf4j
class AdvancedLogger {
    static void main(String[] args) {
        // The @Slf4j annotation provides a 'log' field that can be used
        // for logging at different levels.
        log.info("from Slf4j")

        // We can include exception information in our logs.
        try {
            throw new RuntimeException("Oops!")
        } catch (Exception e) {
            log.error("An error occurred", e)
        }

        // Slf4j supports parameterized logging, which can be more efficient.
        def name = "Groovy"
        def version = "3.0.9"
        log.info("Hello from {} version {}", name, version)
    }
}

// Demonstrate logging to a custom output
class CustomLogger {
    static void main(String[] args) {
        def writer = new StringWriter()
        def printStream = new PrintStream(new WriterOutputStream(writer))
        System.setOut(printStream)

        println "This goes to our custom output"

        System.out.flush()
        println "Custom output: ${writer.toString()}"
    }
}

StandardLogger.main(args)
AdvancedLogger.main(args)
CustomLogger.main(args)

This example demonstrates various logging techniques in Groovy:

  1. We start with the @Log annotation, which provides a simple way to add logging to a class.

  2. We then show how to configure the logger’s output format using system properties.

  3. The @Slf4j annotation is introduced, which provides more advanced logging capabilities.

  4. We demonstrate error logging with exception information.

  5. Parameterized logging is shown, which can be more efficient than string concatenation.

  6. Finally, we show how to log to a custom output stream.

To run this program, save it as logging.groovy and use the groovy command:

$ groovy logging.groovy

The output will vary depending on your Groovy and SLF4J setup, but it should look something like this:

[main] INFO StandardLogger - standard logger
[main] INFO StandardLogger - with date and time
[main] INFO AdvancedLogger - from Slf4j
[main] ERROR AdvancedLogger - An error occurred
java.lang.RuntimeException: Oops!
    at AdvancedLogger.main(logging.groovy:31)
    ...
[main] INFO AdvancedLogger - Hello from Groovy version 3.0.9
Custom output: This goes to our custom output

This example provides a basic introduction to logging in Groovy. In practice, you would typically configure your logging in more detail, possibly using a configuration file, and you might use a more full-featured logging framework like Logback or Log4j.