Coming Up for Air

Gradle Tip: Attaching a Debugger

Tuesday, September 10, 2013 |

Maven offers a nice script to allow for attaching a debugger to your build, mvnDebug. Gradle does not. Again, though, Gradle makes it pretty easy to add this to your build.

Let’s say you want to debug your tests:

build.gradle
1
2
3
4
5
6
test {
    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug',
            '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
    }
}

From the command line, issue gradle -DDEBUG=true test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ gradle -DDEBUG=true test
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
Listening for transport dt_socket at address: 9009
> Building > :test

When you see that line, you can attach the debugger of your choice, using port 9009. This also works if you’re building a command line application:

build.gradle
1
2
3
4
5
6
run {
    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug',
            '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
    }
}

and run:

1
2
3
4
5
6
7
gradle -DDEBUG=true run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
Listening for transport dt_socket at address: 9009
> Building > :run

To add this all of your projects, you can make this change to init.gradle:

$HOME/.gradle/init.gradle

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
allprojects {
    tasks.withType(Test) {
        if (System.getProperty('DEBUG', 'false') == 'true') {
            jvmArgs '-Xdebug',
                '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
        }
    }

    tasks.withType(JavaExec) {
        if (System.getProperty('DEBUG', 'false') == 'true') {
            jvmArgs '-Xdebug',
                '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
        }
    }
}

Search

    Quotes

    Sample quote

    Quote source

    About

    My name is Jason Lee. I am a software developer living in the middle of Oklahoma. I’ve been a professional developer since 1997, using a variety of languages, including Java, Javascript, PHP, Python, Delphi, and even a bit of C#. I currently work for Red Hat on the WildFly/EAP team, where, among other things, I maintain integrations for some MicroProfile specs, OpenTelemetry, Micrometer, Jakarta Faces, and Bean Validation. (Full resume here. LinkedIn profile)

    I am the president of the Oklahoma City JUG, and an occasional speaker at the JUG and a variety of technical conferences.

    On the personal side, I’m active in my church, and enjoy bass guitar, running, fishing, and a variety of martial arts. I’m also married to a beautiful woman, and have two boys, who, thankfully, look like their mother.

    My Links

    Publications