Wednesday, December 11, 2013

Grails Goodness: Debugging App in Forked Mode

Since Grails 2.2 by default the run-app command will launch the Grails application in a separate Java Virtual Machine. This is called forked Tomcat execution in Grails. This way the class path of the Grails build system and the application will not intervene and also both processes will have their own memory settings. We can see the settings in grails-app/conf/BuildConfig.groovy where we find the configuration property grails.project.fork.run. When we want to debug our application in an IDE like IntelliJ IDEA we cannot use the Debug command, because this will only allow us to debug the Grails build system. We will not reach breakpoints in our source code. But Grails 2.3 introduces an extra argument for the run-app command: --debug-fork. If we use this extra argument the JVM running the Grails application will stop and listen for a debug session to be attached and then continue. We can configure a Debug configuration in IntelliJ IDEA (or another IDE) to attach to the waiting Grails application and use breakpoints and other debugging tools like we are used to.

Suppose we have a Grails application named forked-debug and we have created a project in IDEA for this application. We click on the Select Run/Debug Configuration button and select Edit Configurations...:

IDEA opens a dialog where we can change the Grails command and set JVM options. We add the option --debug-fork to the Command Line field in this dialog:

We click the OK button to save our change and close the dialog window. Next we can run our Grails application using our changed run configuration:

IDEA starts our application in the console window we can see Listening for transport dt_socket at address: 5005:

Now it is time to create a new debug configuration. We click on the Select Run/Debug Configuration button again and select Edit Configurations.... We add a new type of configuration, so we click on the + sign and type Remote:

We select the Remote type and the dialog window shows now a lot of input fields which we can leave to the default values. It is good to given this configuration a new name, for example Grails:forked-debug (debug):

We click the OK button to close the dialog window. Our Grails application is still waiting for a debug session to be attached, so we use our new configuration with the Debug button:

In the console window of our Grails application we can see the application is now continuing to start and finally we can reach the application via our web browser. We can now place breakpoints in our source code and when we hit them we can use all debugging tools from IDEA:

We could also have used the argument --debug-fork from a command-line and then use the IDEA debug configuration to attach to that instance of the Grails application.

Code written with Grails 2.3.4 and IntelliJ IDEA 13 is used.