github.com/engineyard/workflow-cli@v2.21.6+incompatible/pkg/logging/log_unix.go (about)

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