Add color to Go log output
Use ANSI escape sequences, Logrus, or a slog-compatible handler, while keeping color codes out of collected logs.
For terminal output, ANSI escape sequences are the simplest option: \033[31m selects red, \033[32m green, and \033[0m resets formatting. Libraries such as Logrus and charmbracelet/log can handle terminal formatting for you.
Write ANSI sequences directly
package main
import "fmt"
const (
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorReset = "\033[0m"
)
func main() {
fmt.Println(colorRed + "ERROR: connection failed" + colorReset)
fmt.Printf("%sINFO%s: startup complete\n", colorGreen, colorReset)
}
Always reset the formatting so later terminal output does not inherit the color.
Use Logrus
Configure its text formatter inside your application:
log.SetFormatter(&log.TextFormatter{ForceColors: true})
log.Warn("Warning message")
Here log refers to github.com/sirupsen/logrus. ForceColors: true forces color even when the output is not a terminal. Omit that setting to use the formatter's normal terminal detection, or set DisableColors: true for a plain-text destination.
Use a handler with slog
Go 1.21 introduced log/slog. Its built-in text and JSON handlers do not add color. A compatible third-party handler, such as charmbracelet/log, can provide terminal styling while retaining structured attributes.
Keep collected logs plain
Disable color when writing to files or forwarding logs to a collector. Otherwise, the escape bytes become part of the stored message. Terminal support depends on the terminal host and its configuration; running PowerShell alone does not guarantee ANSI rendering on every Windows console.
How can I clean up existing color codes?
A pattern such as \x1b\[[0-9;]*m removes common SGR color sequences. It is not a general ANSI parser and does not cover every terminal-control sequence. Preventing the codes at the logger is preferable.
See the Logrus formatter documentation and Charm log documentation for their handler options.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan