How to use log4j in gradle task

I tried using log4j annotation. The log statements are working fine with simpe Groovy file. But when i try to use them with gradle task. It is not getting printed.

Groovy file :

@Log4j
class HelloWorldLog {
   static void main(args) {
       log.info "Hello world"
    }
 }

Gradle task:

@Log4j
    class DeployTask extends DefaultTask {
       @TaskAction
       def deployTaskAction(){
            log.info "DeployTask!!!"
       }
   }

and i use same log4j.properties file for both. How to enable Gradle task log statements? Thanks

Task implementations already expose a logger.

http://www.gradle.org/docs/current/dsl/org.gradle.api.Task.html#org.gradle.api.Task:logger

So you just need to use:

logger.info “DeployTask!!!”

I’m getting the output in console… Not the file i mentioned in log4j.properties

How to make it to print the logging statement to a log file. instead of printing tat to a console?? Thanks.

Reconfiguring Gradle’s logging this way is not supported.

Then how to write the logs to files? Is there any ways to achieve this?

You can redirect the console output to a file. Or you can open a file and write to it.

I will elaborate a bit on what Jeevi has stated. It seems we can collect the Std Out and Err by setting the stream (as seen in the sample) so that is not much of an issue.

import java.io.File;
import org.gradle.tooling.*;
import groovy.util.logging.*;
  @Log4j
public class BuildLauncherTest {
      public static void main(String[] args) {
        ProjectConnection connection = GradleConnector.newConnector()
                .useInstallation(new File("/software/gradle-1.3"))
                .forProjectDirectory(new File("/temp/dummyBuild"))
                .connect();
        log.info("Starting the build using the Gradle BuildLauncher...")
        BuildLauncher build = connection.newBuild();
        build.forTasks("hello");
          // Problem 1. uncomment after renaming the build.gradle to myBuild.gradle and comment the other line below
        //build.withArguments("-b", "myBuild.gradle", "-i");
        build.withArguments("-i"); // This works
    // Problem 2. Also using the plugin the standard build.gradle script also doesn't work
 //build.withArguments("-I", "../../pluginscript.gradle", "-i");
          def stream = new ByteArrayOutputStream()
        build.setStandardError(stream);
        build.setStandardOutput(stream)
        build.run();
        // now we can log each line gathered in the stream
        log.info("Build Out/Err Begin " + stream + " Build Out/Err END ")
        log.info("Build run....DONEEEEEEEEE");
        System.out.println("Build run....DONEEEEEEEEE");
    }
}

The real problem appears to be with the log stmts. It seems the log4j or the logger is working as expected when run from the command line but not from the Tooling API.

Here is the build script that i tried (build.gradle)

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import groovy.util.logging.Log4j;
  @Log4j
class HelloTask extends DefaultTask {
    @TaskAction
    def hello() {
        println 'using println to say Hello world'
        log.warn 'using log4j-warn to say Hello world'
        log.info 'using log4j-info to say Hello world'
                  logger.warn 'using gradle logger-warn to say Hello world'
        logger.lifecycle 'using grade logger-lifecycle to say Hello world'
        logger.info 'using grade logger-info to say Hello world'
    }
}
  project.tasks.add("hello", HelloTask.class)
  //apply plugin: 'helloplugin'

From the command line, with the above script, I got the expected output from the loggers. Then I moved the HelloTask code into a plugin. And it also works perfectly fine with output as below:

D:\temp\dummyBuild>gradle -I d:\pluginscript.gradle hello -i
Starting Build
Settings evaluated using empty settings script.
Projects loaded. Root project using build file 'D:\temp\dummyBuild\build.gradle'
.
Included projects: [root project 'dummyBuild']
Evaluating root project 'dummyBuild' using build file 'D:\temp\dummyBuild\build.
gradle'.
Inside HelloPlugin...
All projects evaluated.
Selected primary task 'hello'
Tasks to be executed: [task ':hello']
:hello
Task ':hello' has not declared any outputs, assuming that it is out-of-date.
using println to say Hello world
using log4j-warn to say Hello world
using log4j-info to say Hello world
using gradle logger-warn to say Hello world
using grade logger-lifecycle to say Hello world
using grade logger-info to say Hello world
  BUILD SUCCESSFUL
  Total time: 1.449 secs

Running from command line has no issues. There appears to be 2 problems with Tooling API.

Problem 1. When you use a different script name like myBuild.gradle (i.e. other than build.gradle) you have issues in logging. As seen from output it has ommitted output with INFO logLevel.

19:25:58.687 [main] DEBUG org.gradle.tooling.GradleConnector - Connecting from tooling API consumer version 1.3
19:25:58.722 [Connection worker] DEBUG o.g.t.i.c.l.DefaultToolingImplementationLoader - Using tooling provider from Gradle installation '\software\gradle-1.3'
19:25:58.723 [Connection worker] DEBUG o.g.t.i.c.l.DefaultToolingImplementationLoader - Using tooling provider classpath: [\software\gradle-1.3\lib\ant-1.8.4.jar, \software\gradle-1.3\lib\ant-launcher-1.8.4.jar, \software\gradle-1.3\lib\asm-all-4.0.jar, \software\gradle-1.3\lib\commons-collections-3.2.1.jar, \software\gradle-1.3\lib\commons-io-1.4.jar, \software\gradle-1.3\lib\commons-lang-2.6.jar, \software\gradle-1.3\lib\dom4j-1.6.1.jar, \software\gradle-1.3\lib\gradle-base-services-1.3.jar, \software\gradle-1.3\lib\gradle-base-services-groovy-1.3.jar, \software\gradle-1.3\lib\gradle-cli-1.3.jar, \software\gradle-1.3\lib\gradle-core-1.3.jar, \software\gradle-1.3\lib\gradle-launcher-1.3.jar, \software\gradle-1.3\lib\gradle-messaging-1.3.jar, \software\gradle-1.3\lib\gradle-native-1.3.jar, \software\gradle-1.3\lib\gradle-open-api-1.3.jar, \software\gradle-1.3\lib\gradle-tooling-api-1.3.jar, \software\gradle-1.3\lib\gradle-ui-1.3.jar, \software\gradle-1.3\lib\gradle-wrapper-1.3.jar, \software\gradle-1.3\lib\groovy-all-1.8.6.jar, \software\gradle-1.3\lib\guava-11.0.2.jar, \software\gradle-1.3\lib\ivy-2.2.0.jar, \software\gradle-1.3\lib\jansi-1.2.1.jar, \software\gradle-1.3\lib\jarjar-1.3.jar, \software\gradle-1.3\lib\javax.inject-1.jar, \software\gradle-1.3\lib\jaxen-1.1.jar, \software\gradle-1.3\lib\jcip-annotations-1.0.jar, \software\gradle-1.3\lib\jcl-over-slf4j-1.6.6.jar, \software\gradle-1.3\lib\jna-3.2.7.jar, \software\gradle-1.3\lib\jna-posix-1.0.3.jar, \software\gradle-1.3\lib\jsch-0.1.46.jar, \software\gradle-1.3\lib\jul-to-slf4j-1.6.6.jar, \software\gradle-1.3\lib\log4j-over-slf4j-1.6.6.jar, \software\gradle-1.3\lib\logback-classic-1.0.6.jar, \software\gradle-1.3\lib\logback-core-1.0.6.jar, \software\gradle-1.3\lib\native-platform-0.2.jar, \software\gradle-1.3\lib\native-platform-linux-amd64-0.2.jar, \software\gradle-1.3\lib\native-platform-linux-i386-0.2.jar, \software\gradle-1.3\lib\native-platform-osx-universal-0.2.jar, \software\gradle-1.3\lib\native-platform-windows-amd64-0.2.jar, \software\gradle-1.3\lib\native-platform-windows-i386-0.2.jar, \software\gradle-1.3\lib\slf4j-api-1.6.6.jar]
19:25:58.788 [Connection worker] DEBUG o.g.t.i.provider.DefaultConnection - Provider implementation created.
19:25:58.830 [Connection worker] DEBUG o.g.t.i.provider.DefaultConnection - Embedded executer support created.
19:25:58.835 [Connection worker] DEBUG o.g.t.i.provider.DefaultConnection - Configuring logging to level: INFO
Tooling API uses target gradle version: 1.3.
Connected to the daemon. Dispatching Build{id=c00a758f-2ebf-46e6-a0bc-5057f8e91158.1, currentDir=D:\workspace\groovy\testG} request.
:hello
using println to say Hello world
using log4j-warn to say Hello world
using gradle logger-warn to say Hello world
using grade logger-lifecycle to say Hello world
  BUILD SUCCESSFUL
  Total time: 0.465 secs
Build run....DONEEEEEEEEE

If you have the regular build.gradle as the script name then logs are OK.

Problem 2. When the HelloTask is moved to plugin, then execution of build.gradle is also not working as expected. So the build script (build.gradle) is just one liner and all the code is in the plugin.

apply plugin: 'helloplugin'

Can one of the gradle team members confirm if this is a bug with Tooling API? We are using filenames other than build.gradle and all the tasks are defined in the plugin. It seems like Log Level ‘lifecyle’ upwards only is printed ignoring INFO and below. But in the output it says Configuring logging to level: INFO as seen in the output above.

Thanks, -Harshad.

I’m a beginner asking a question: I read through this excellent explanation but I don’t understand how you actually loaded a build.gradle file that is not called “build.gradle”. How did you customize that?

You can have the build script with any name. You can then say:

gradle -b myBuild.gradle <taskName>

Likewise you can pass the Arguments in BuildLauncher – Tooling API (as seen in my code above).

Hi Harshad,

I’m splitting this off to a different topic so we can track it more effectively. Please reference the new topic here: Logging output is different when using Tooling API and non standard build scr…