Azure DevOps pipelines: how to set font color from C#

When we work DevOps pipelines, pipeline logs often help us diagnose what went wrong or right. An easy way to make text stand out is to put some colors. You might notice how a red text instantly directs our attention to errors in a haystack of text.

In Azure DevOps, one way to write text in color is to use Logging Commands:

Screenshot of logs with custom formatting options
Text displayed using Logging Commands will by formatted in color by default:

Logging Commands seem a good choice if we want to put emphasis on some part of logs which has a semantic meaning matching one of the above categories. But using above commands might also have side effects. For example, a warning displayed this way will also be exposed in other places in DevOps UI, and sometimes we might want to avoid it.

So how do we add color without adding any extra meaning? I experimented a bit and here are my observations.

The following code does not render in color in DevOps pipelines:

// render the default font Console.WriteLine("Normal style"); // the standard C# way: it works in console, but not in DevOps pipelines Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Console.ForegroundColor = ConsoleColor.Cyan"); Console.BackgroundColor = ConsoleColor.Yellow; Console.WriteLine("Console.BackgroundColor = ConsoleColor.Yellow"); Console.ResetColor();
Code language: C# (cs)
Console.ForegroundColor and Console.BackgroundColor might work in console window, but not in DevOps pipelines

But the below code will render text in color:

// use escape sequence to change font style for (int fontColor = 30; fontColor <= 37; fontColor++) Console.WriteLine($"Style {fontColor} \u001b[{fontColor}m example \u001b[0m reset");
Code language: C# (cs)
Escape sequences work both in console and DevOps pipelines

Wikipedia article on ANSI escape codes shows how numbers map to to specific styles. In general, based on my observations, DevOps seems to currently support escape sequences that set foreground or background color and nothing more.

The colors that are rendered as a result are pretty much the same in DevOps as in Windows command line with default settings. So red will be red and green will be green in both places etc. It therefore seems good to use them in conventions like “32 = green = ok” or “33 = yellow = warning”.

Have fun!

Leave a Comment