Logging in Groovy Script

2020-05-21 11:28发布

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.

4条回答
小情绪 Triste *
2楼-- · 2020-05-21 11:40

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"
查看更多
做个烂人
3楼-- · 2020-05-21 11:43

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

查看更多
冷血范
4楼-- · 2020-05-21 11:49

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()
查看更多
你好瞎i
5楼-- · 2020-05-21 11:55

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.

查看更多
登录 后发表回答