diff --git a/log_nix.go b/log_nix.go index f06a871..4ff2ab1 100644 --- a/log_nix.go +++ b/log_nix.go @@ -16,37 +16,38 @@ import ( type color int const ( - colorBlack = iota + 30 - colorRed - colorGreen - colorYellow - colorBlue - colorMagenta - colorCyan - colorWhite + ColorBlack = iota + 30 + ColorRed + ColorGreen + ColorYellow + ColorBlue + ColorMagenta + ColorCyan + ColorWhite ) var ( colors = []string{ - CRITICAL: colorSeq(colorMagenta), - ERROR: colorSeq(colorRed), - WARNING: colorSeq(colorYellow), - NOTICE: colorSeq(colorGreen), - DEBUG: colorSeq(colorCyan), + CRITICAL: ColorSeq(ColorMagenta), + ERROR: ColorSeq(ColorRed), + WARNING: ColorSeq(ColorYellow), + NOTICE: ColorSeq(ColorGreen), + DEBUG: ColorSeq(ColorCyan), } boldcolors = []string{ - CRITICAL: colorSeqBold(colorMagenta), - ERROR: colorSeqBold(colorRed), - WARNING: colorSeqBold(colorYellow), - NOTICE: colorSeqBold(colorGreen), - DEBUG: colorSeqBold(colorCyan), + CRITICAL: ColorSeqBold(ColorMagenta), + ERROR: ColorSeqBold(ColorRed), + WARNING: ColorSeqBold(ColorYellow), + NOTICE: ColorSeqBold(ColorGreen), + DEBUG: ColorSeqBold(ColorCyan), } ) // LogBackend utilizes the standard log module. type LogBackend struct { - Logger *log.Logger - Color bool + Logger *log.Logger + Color bool + ColorConfig []string } // NewLogBackend creates a new LogBackend. @@ -57,8 +58,13 @@ func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend { // Log implements the Backend interface. func (b *LogBackend) Log(level Level, calldepth int, rec *Record) error { if b.Color { + col := colors[level] + if len(b.ColorConfig) > int(level) && b.ColorConfig[level] != "" { + col = b.ColorConfig[level] + } + buf := &bytes.Buffer{} - buf.Write([]byte(colors[level])) + buf.Write([]byte(col)) buf.Write([]byte(rec.Formatted(calldepth + 1))) buf.Write([]byte("\033[0m")) // For some reason, the Go logger arbitrarily decided "2" was the correct @@ -69,11 +75,26 @@ func (b *LogBackend) Log(level Level, calldepth int, rec *Record) error { return b.Logger.Output(calldepth+2, rec.Formatted(calldepth+1)) } -func colorSeq(color color) string { +// ConvertColors takes a list of ints representing colors for log levels and +// converts them into strings for ANSI color formatting +func ConvertColors(colors []int, bold bool) []string { + converted := []string{} + for _, i := range colors { + if bold { + converted = append(converted, ColorSeqBold(color(i))) + } else { + converted = append(converted, ColorSeq(color(i))) + } + } + + return converted +} + +func ColorSeq(color color) string { return fmt.Sprintf("\033[%dm", int(color)) } -func colorSeqBold(color color) string { +func ColorSeqBold(color color) string { return fmt.Sprintf("\033[%d;1m", int(color)) }