Gradle Cheat Sheet (8): Logging

1. Log Levels

  Gradle定义了6个log等级:

ERROR Error messages
QUIET Important information messages
WARNING Warning messages
LIFECYCLE Progress information messages
INFO Information messages
DEBUG Debug messages

  Gradle会把标准输出重定向到QUIET等级的log。可以使用logger输出指定等级的log,如:

task logTest(type: LogTask)

class LogTask extends DefaultTask {
    @TaskAction
    void doAction() {
        println 'start'
        logger.quiet 'Log at quiet level'
        logger.warn 'Log at warning level'
        logger.lifecycle 'Log at lifecycle level'
        logger.info 'Log at info level'
        logger.debug 'Log at debug level'
    }
}

  可以使用命令行选项设置要查看的log等级:

no logging options LIFECYCLE and higher
-q or –quiet QUIET and higher
-i or –info INFO and higher
-d or –debug DEBUG and higher (that is, all log messages)

  直接运行任务:

$ gradle logTest

输出为:

:logTest
start
Log at quiet level
Log at warning level
Log at lifecycle level

可见只有LIFECYCLE等级以上的log被打印出来。

  加入–debug 参数运行:

$ gradle logTest --debug

会看到大量log,可以使用grep (Linux)或findstr (Windows)查找关心的内容:

$ gradle logTest --debug | grep 'Log at debug'

输出为:

14:34:03.710 [DEBUG] [org.gradle.api.Task] Log at debug level

2. Stacktrace Logging

  当脚本运行失败时,Gradle默认是不打印Stacktrace的,可以使用如下的命令行选项来打印Stacktrace:

No stacktrace options No stacktraces are printed to the console in case of a build error (e.g. a compile error). Only in case of internal exceptions will stacktraces be printed. If the DEBUG log level is chosen, truncated stacktraces are always printed.
-s or –stacktrace Truncated stacktraces are printed. We recommend this over full stacktraces. Groovy full stacktraces are extremely verbose (Due to the underlying dynamic invocation mechanisms. Yet they usually do not contain relevant information for what has gone wrong in your code.)
-S or –full-stacktrace The full stacktraces are printed out.

 

  更多内容可以参考这里