diff --git a/color.go b/color.go index fdace8f..bb3409c 100644 --- a/color.go +++ b/color.go @@ -1,70 +1,29 @@ package log -import "text/template" +import ( + "fmt" + "strconv" + "text/template" -type Attribute int - -// Base attributes -const ( - Reset Attribute = iota - Bold - Faint - Italic - Underline - BlinkSlow - BlinkRapid - ReverseVideo - Concealed - CrossedOut + "kumoly.io/core/log/color" ) -// Foreground text colors -const ( - FgBlack Attribute = iota + 30 - FgRed - FgGreen - FgYellow - FgBlue - FgMagenta - FgCyan - FgWhite -) - -// Foreground Hi-Intensity text colors -const ( - FgHiBlack Attribute = iota + 90 - FgHiRed - FgHiGreen - FgHiYellow - FgHiBlue - FgHiMagenta - FgHiCyan - FgHiWhite -) - -// Background text colors -const ( - BgBlack Attribute = iota + 40 - BgRed - BgGreen - BgYellow - BgBlue - BgMagenta - BgCyan - BgWhite -) - -// Background Hi-Intensity text colors -const ( - BgHiBlack Attribute = iota + 100 - BgHiRed - BgHiGreen - BgHiYellow - BgHiBlue - BgHiMagenta - BgHiCyan - BgHiWhite -) +func (l *Logger) M(s string, attrs ...color.Attribute) string { + if !l.color { + return s + } + style := "" + for i, v := range attrs { + if i >= 3 { + break + } + if i > 0 { + style += ";" + } + style = style + strconv.Itoa(int(v)) + } + return fmt.Sprintf("\033[%sm%s\033[0m", style, s) +} func setColorMap(funcMap template.FuncMap, color bool) { if color { diff --git a/color/color.go b/color/color.go new file mode 100644 index 0000000..343c733 --- /dev/null +++ b/color/color.go @@ -0,0 +1,65 @@ +package color + +type Attribute int + +// Base attributes +const ( + Reset Attribute = iota + Bold + Faint + Italic + Underline + BlinkSlow + BlinkRapid + ReverseVideo + Concealed + CrossedOut +) + +// Foreground text colors +const ( + FgBlack Attribute = iota + 30 + FgRed + FgGreen + FgYellow + FgBlue + FgMagenta + FgCyan + FgWhite +) + +// Foreground Hi-Intensity text colors +const ( + FgHiBlack Attribute = iota + 90 + FgHiRed + FgHiGreen + FgHiYellow + FgHiBlue + FgHiMagenta + FgHiCyan + FgHiWhite +) + +// Background text colors +const ( + BgBlack Attribute = iota + 40 + BgRed + BgGreen + BgYellow + BgBlue + BgMagenta + BgCyan + BgWhite +) + +// Background Hi-Intensity text colors +const ( + BgHiBlack Attribute = iota + 100 + BgHiRed + BgHiGreen + BgHiYellow + BgHiBlue + BgHiMagenta + BgHiCyan + BgHiWhite +) diff --git a/log_test.go b/log_test.go index ac4f392..b9c72fd 100644 --- a/log_test.go +++ b/log_test.go @@ -4,6 +4,8 @@ import ( "io" "os" "testing" + + c "kumoly.io/core/log/color" ) func TestDev(t *testing.T) { @@ -78,6 +80,12 @@ func TestCustTmpl(t *testing.T) { l.InfoF(H{"Test": "set"}, "d", "sdf", "sdfsdf") } +func TestColoring(t *testing.T) { + l := Sub("color") + l.Error(l.M("Hello", c.BgHiGreen, c.Italic, c.FgWhite), ", ", l.M("world", c.FgBlue, c.BgHiYellow)) + l.Error(l.M("Hello", c.FgHiGreen), ", ", l.M("world", c.Underline, c.FgMagenta)) +} + func TestToFile(t *testing.T) { PROD = true l := Sub("TestToFile")