How do I intercept or elevate log messages when calling an Ant task from Gradle

泄露秘密 提交于 2020-01-13 10:09:09

问题


I call ant.signjar from a gradle script. How can I capture its output? I did neither get it managed easily to elevate the output from INFO to another level, nor to intercept or wrap the output to error warnings out to WARN level. Currently the signjar echoes out that the certificate will expire soon, but this is not shown on WARN level which is not so nice.


回答1:


I assume the Ant task is using Ant's logging framework, and not just printing to standard out. In that case, have you tried the following?

task taskThatCallsAntTask {
    logging.level = LogLevel.INFO
}

When configured in this way, the log level will be changed to INFO while the task is executing (and reverted back afterwards), no matter which log level is set when invoking Gradle. Note that you can't elevate the log level of an Ant log event; it's up to the Ant task at which level it logs.




回答2:


Here's a method that captures the output of an Ant task by registering a custom BuildListener for the duration of the call.

def captureAntOutput(ant, Closure command) {
    def buffer = new ByteArrayOutputStream()
    def captureStream = new PrintStream(buffer, true, "UTF-8")
    def listener = new org.apache.tools.ant.DefaultLogger(
            errorPrintStream: captureStream,
            outputPrintStream: captureStream,
            messageOutputLevel: org.apache.tools.ant.Project.MSG_INFO
    )

    ant.project.addBuildListener(listener)
    project.configure(ant, command)
    ant.project.removeBuildListener(listener)

    return buffer.toString("UTF-8");
}

Example usage:

String result = captureAntOutput(ant) {
    echo(message: "hello")
}
assert result.contains("hello")


来源:https://stackoverflow.com/questions/11413559/how-do-i-intercept-or-elevate-log-messages-when-calling-an-ant-task-from-gradle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!