feat: add color text

master
Evan Chen 2021-11-02 15:55:52 +08:00
parent e247f30f45
commit fe5297699f
3 changed files with 94 additions and 62 deletions

View File

@ -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 {

65
color/color.go Normal file
View File

@ -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
)

View File

@ -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")