Gradle color output

Just additional informations completing the accepted answer. Here is the default styles with gradle 4.10

StyledTextOutput.Style.values().each {
    out.style(it).println("This line has the style $it")
}

all styles

Moreoever, you can create multicolor line, like a StringBuilder

out.style(Style.ProgressStatus).text('This is ').style(Style.Failure).text('a multicolor ').style(Style.Identifier).println('line')

multicolor

edit : here is a working example :

import org.gradle.internal.logging.text.StyledTextOutput 
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.internal.logging.text.StyledTextOutput.Style

def out = services.get(StyledTextOutputFactory).create("an-ouput")

out.style(Style.ProgressStatus).text('This is ').style(Style.Failure).text('a multicolor ').style(Style.Identifier).println('line')

Is there a simple way to tap into the color printing powers of Gradle/Groovy without importing a lot of packages?

In the interest of exploring more options, without importing packages, you could just use straight ANSI escape codes (not a strictly Gradle/Groovy technology), to format your output. The following is a working example:

task myTask {
    def styler = 'black red green yellow blue magenta cyan white'
        .split().toList().withIndex(30)
        .collectEntries { key, val -> [(key) : { "\033[${val}m${it}\033[0m" }] }

    doLast {
        println "Message: ${styler['red']('Hello')} ${styler['blue']('World')}"
    }
}

Complete code on GitHub


Found the answer! According to this gradle forum post, there's no public interface for coloring the output of the logger. You are free to use the internal classes, but those may change in future versions. In the gradle script, put at the top:

Older Gradle:

import org.gradle.logging.StyledTextOutput;
import org.gradle.logging.StyledTextOutputFactory;
import static org.gradle.logging.StyledTextOutput.Style;

Gradle 3.3+:

import org.gradle.internal.logging.text.StyledTextOutput;
import org.gradle.internal.logging.text.StyledTextOutputFactory;
import static org.gradle.internal.logging.text.StyledTextOutput.Style;

(I still haven't figured out how to move this to the init.gradle file.) Then shortly after, define

def out = services.get(StyledTextOutputFactory).create("blah")

I'm still not sure what needs to be in the create method's string (it doesn't seem to affect anything yet). Then later in your task,

out.withStyle(Style.Info).println('colored text')

This should work with all the categories: normal, header, userinput, identifier, description, progressstatus, failure, info, and error. An additional step if you want to customize the color of each category, add the following to an init.gradle file in your ~/.gradle directory (or other options):

System.setProperty('org.gradle.color.error', 'RED')

and then replace the "error" category with any from the above list.