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 package log
import "text/template" import (
"fmt"
"strconv"
"text/template"
type Attribute int "kumoly.io/core/log/color"
// Base attributes
const (
Reset Attribute = iota
Bold
Faint
Italic
Underline
BlinkSlow
BlinkRapid
ReverseVideo
Concealed
CrossedOut
) )
// Foreground text colors func (l *Logger) M(s string, attrs ...color.Attribute) string {
const ( if !l.color {
FgBlack Attribute = iota + 30 return s
FgRed }
FgGreen style := ""
FgYellow for i, v := range attrs {
FgBlue if i >= 3 {
FgMagenta break
FgCyan }
FgWhite if i > 0 {
) style += ";"
}
// Foreground Hi-Intensity text colors style = style + strconv.Itoa(int(v))
const ( }
FgHiBlack Attribute = iota + 90 return fmt.Sprintf("\033[%sm%s\033[0m", style, s)
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 setColorMap(funcMap template.FuncMap, color bool) { func setColorMap(funcMap template.FuncMap, color bool) {
if color { 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" "io"
"os" "os"
"testing" "testing"
c "kumoly.io/core/log/color"
) )
func TestDev(t *testing.T) { func TestDev(t *testing.T) {
@ -78,6 +80,12 @@ func TestCustTmpl(t *testing.T) {
l.InfoF(H{"Test": "set"}, "d", "sdf", "sdfsdf") 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) { func TestToFile(t *testing.T) {
PROD = true PROD = true
l := Sub("TestToFile") l := Sub("TestToFile")