Search

Dark theme | Light theme

June 17, 2016

Grails Goodness: Adding Custom Info To Info Endpoint

In a previous post we learned how to add Git commit information to the /info endpoint in our Grails application. We can add our own custom information to this endpoint by defining application properties that start with info..

Let's add the Grails environment the application runs in to the /info endpoint. We create the file grails-app/conf/application.groovy. To get the value we must have a piece of code that is executed so using the application.groovy makes this possible instead of a static configuration file like application.yml:

// File: grails-app/conf/application.groovy
import grails.util.Environment

// Property info.app.grailsEnv.
// Because it starts with info. it ends
// up in the /info endpoint.
info {
    app {
        grailsEnv = Environment.isSystemSet() ? Environment.current.name : Environment.PRODUCTION.name
    }
}

We also want to have information available at build time to be included. Therefore we write a new Gradle task in our build.gradle that create an application.properties file in the build directory. The contents is created when we run or build our Grails application. We just have to make sure the properties stored in application.properties start with info.:

// File: build.gradle
...
task buildInfoProperties() {
    ext {
        buildInfoPropertiesFile = 
            file("$buildDir/resources/main/application.properties")
        
        info = [
            // Look for System environment variable BUILD_TAG.    
            tag: System.getenv('BUILD_TAG') ?: 'N/A', 
            // Use current date.    
            time: new Date().time,
            // Get username from System properties.    
            by: System.properties['user.name']]
    }
    
    inputs.properties info
    outputs.file buildInfoPropertiesFile

    doFirst {
        buildInfoPropertiesFile.parentFile.mkdirs()
        
        ant.propertyfile(file: ext.buildInfoPropertiesFile) {
            for(me in info) {
                entry key: "info.buildInfo.${me.key}", value: me.value
            }
        }
    }
}
processResources.dependsOn(buildInfoProperties)

// Add extra information to be saved in application.properties.
buildInfoProperties.info.machine = "${InetAddress.localHost.hostName}"
...

Let's run our Grails application:

$ export BUILD_TAG=jenkins-grails_app-42 
$ grails run-app
...
| Running application...
Grails application running at http://localhost:8080 in environment: development

And we look at the output of the /info endpoint:

$ http --body http://localhost:8080/info
{
    "app": {
        "grailsEnv": "development",
        "grailsVersion": "3.1.8",
        "name": "grails-gitinfo",
        "version": "1.0.0.DEVELOPMENT"
    },
    "buildInfo": {
        "by": "mrhaki",
        "machine": "mrhaki-laptop-2015.local",
        "time": "1466173858064",
        "tag": "jenkins-grails_app-42"
    }
}
$

Written with Grails 3.1.8.