-
Notifications
You must be signed in to change notification settings - Fork 0
/
colorizer.go
67 lines (56 loc) · 1.43 KB
/
colorizer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package io
import (
cio "io"
"strings"
)
// Colorizer is a Colorizing logger middleman.
//
// This can be used to colorize logs as they pass through to another writer. The
// colorization uses the UNIX-style shell color coding.
//
// TODO: This is a very basic implementation, and could use some TLC.
//
// Example Usage:
//
// import (
// "github.com/Masterminds/cookoo"
// "github.com/Masterminds/cookoo/io"
// // And other stuff
// cio "io"
// )
// func main() {
// reg, router, cxt := cookoo.Cookoo()
// clogger := io.NewColorizer(cio.Stdout)
// cxt.AddLogger("stdout", clogger)
// // etc.
// }
//
// Given the above, log messages will be colorized before written
// to `io.Stdout`.
type Colorizer struct {
writer cio.Writer
}
// NewColorizer creates a new colorizer that wraps a given io.Writer.
func NewColorizer(writer cio.Writer) *Colorizer {
c := new(Colorizer)
c.writer = writer
return c
}
// Write colorizes a message and then passes it to the underlying writer.
func (r *Colorizer) Write(data []byte) (int, error) {
str := string(data)
if strings.HasPrefix(str, "error") {
str = "\033[0;31m" + str + "\033[m"
} else if strings.HasPrefix(str, "warn") {
str = "\033[0;33m" + str + "\033[m"
} else if strings.HasPrefix(str, "info") {
str = "\033[0;36m" + str + "\033[m"
}
wlen, err := r.writer.Write([]byte(str))
dlen := len(data)
// Short write.
if wlen < dlen {
return wlen, err
}
return dlen, err
}