generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
plain.go
70 lines (60 loc) · 1.26 KB
/
plain.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
68
69
70
package log
import (
"fmt"
"io"
"os"
"time"
"github.com/mattn/go-isatty"
)
var colours = map[Level]string{
Trace: "\x1b[90m", // Dark gray
Debug: "\x1b[34m", // Blue
Info: "\x1b[37m", // White
Warn: "\x1b[33m", // Yellow
Error: "\x1b[31m", // Red
}
var _ Sink = (*plainSink)(nil)
func newPlainSink(w io.Writer, logTime bool, alwaysColor bool) *plainSink {
var isaTTY bool
if alwaysColor {
isaTTY = true
} else if f, ok := w.(*os.File); ok {
isaTTY = isatty.IsTerminal(f.Fd())
}
return &plainSink{
isaTTY: isaTTY,
w: w,
logTime: logTime,
}
}
type plainSink struct {
isaTTY bool
w io.Writer
logTime bool
}
// Log implements Sink
func (t *plainSink) Log(entry Entry) error {
var prefix string
// Add timestamp if required
if t.logTime {
prefix += entry.Time.Format(time.TimeOnly) + " "
}
// Add scope if required
scope, exists := entry.Attributes[scopeKey]
if exists {
prefix += entry.Level.String() + ":" + scope + ": "
} else {
prefix += entry.Level.String() + ": "
}
// Print
var err error
if t.isaTTY {
_, err = fmt.Fprintf(t.w, "%s%s%s\x1b[0m\n", colours[entry.Level], prefix, entry.Message)
} else {
_, err = fmt.Fprintf(t.w, "%s%s\n", prefix, entry.Message)
}
if err != nil {
return err
}
return nil
}