Working with scripts is always useful, especially when we want to automate a lot of things. But most of this scripts generates a lot of logs to be able to follow what's going on. But having so much logs doesn't help when we want to see what happend during the pipeline, and see quickly if something wrong happend.
That's why today we will see how to add color in your life and your logs!
How to do it?
In this example, the code is in Go, but it will work for every system printing their logs in a Bash Console.
To change the color of a text, you just need to add something which looks like this : \033[31m
This little string is what we need to change the text color. The two last numbers are the one which helps us to choose the color to display. In this example, the selected color is red.
Example with all colors
package main
var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Purple = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"
func main() {
println(White + "This is White" + Reset)
println(Red + "This is Red" + Reset)
println(Green + "This is Green" + Reset)
println(Yellow + "This is Yellow" + Reset)
println(Blue + "This is Blue" + Reset)
println(Purple + "This is Purple" + Reset)
println(Cyan + "This is Cyan" + Reset)
println(Gray + "This is Gray" + Reset)
}
In this example, you can ask "Why is there some Reset
at the end of each line?"
The response is simple: It's a good practice to avoid color issues.
If you forget to reset the color and you don't define another one, the defined color will continue to be used for the following logs!
Example
package main
var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Purple = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"
func main() {
println(White + "This is White")
println("This is Red" + Reset)
println(Green + "This is Green" + Reset)
println(Yellow + "This is Yellow")
println("This is Blue" + Reset)
println(Purple + "This is Purple" + Reset)
println(Cyan + "This is Cyan" + Reset)
println(Gray + "This is Gray" + Reset)
}
Conclusion
Now you know how to have colors in your logs, and I hope it will help you in your following pipelines and/or scripts!
Top comments (0)