github.com/drycc/workflow-cli@v1.5.3-0.20240322092846-d4ee25983af9/pkg/logging/log_unix.go (about) 1 //go:build linux || darwin 2 // +build linux darwin 3 4 package logging 5 6 import ( 7 "fmt" 8 "io" 9 "strings" 10 11 "github.com/drycc/pkg/prettyprint" 12 ) 13 14 const colorStringEscape = "\033[3%dm" 15 16 // Choose an ANSI color by converting a string to an int. 17 // 18 // Color 5, magenta, reserved for controller log messages. 19 // 20 // Colors 0 and 7, black and white, are skipped because they are likely to be unreadable 21 // against terminal backgrounds. Instead, 9, the default text color is used, likely to be the color 22 // of the two that is readable against the terminal background. 23 func chooseColor(input string) string { 24 if input == "INFO" { 25 return fmt.Sprintf(colorStringEscape, 5) 26 } 27 28 var sum uint8 29 30 for _, char := range []byte(input) { 31 sum += uint8(char) 32 } 33 34 // Eight possible terminal colors, but Black and White are excluded 35 color := (sum % 6) + 1 36 37 // Color 5 is reserved, replace it with default text color. 38 if color == 5 { 39 color = 9 40 } 41 42 return fmt.Sprintf(colorStringEscape, color) 43 } 44 45 // PrintLog prints a log line with a color matched to its category. 46 func PrintLog(out io.Writer, log string) { 47 parts := strings.Split(strings.Split(log, " -- ")[0], " ") 48 category := parts[0] 49 colorVars := map[string]string{ 50 "Color": chooseColor(category), 51 "Log": log, 52 } 53 fmt.Fprintln(out, prettyprint.ColorizeVars("{{.V.Color}}{{.V.Log}}{{.C.Default}}", colorVars)) 54 }