-
Notifications
You must be signed in to change notification settings - Fork 1
/
filehandler.go
71 lines (62 loc) · 1.19 KB
/
filehandler.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
71
package log
import (
"fmt"
"os"
"strings"
"sync"
"github.com/mattn/go-isatty"
)
// FileHandler is a handler implementation that writes the logging output to a *os.File.
// If given file is a tty, output will be colored.
type FileHandler struct {
*BaseHandler
f *os.File
m sync.Mutex
isatty bool
}
func NewFileHandler(f *os.File) *FileHandler {
return &FileHandler{
BaseHandler: NewBaseHandler(),
f: f,
isatty: isatty.IsTerminal(f.Fd()),
}
}
func (h *FileHandler) Handle(rec *Record) {
message := h.BaseHandler.FilterAndFormat(rec)
if message == "" {
return
}
if !strings.HasSuffix(message, "\n") {
message += "\n"
}
if h.isatty && LevelColors[rec.Level] != NOCOLOR {
message = fmt.Sprintf("\033[%dm%s\033[0m", LevelColors[rec.Level], message)
}
h.m.Lock()
fmt.Fprint(h.f, message)
h.m.Unlock()
}
func (h *FileHandler) Close() error {
return h.Close()
}
type Color int
// Colors for different log levels.
const (
BLACK Color = iota + 30
RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
WHITE
NOCOLOR = -1
)
var LevelColors = map[Level]Color{
CRITICAL: MAGENTA,
ERROR: RED,
WARNING: YELLOW,
NOTICE: GREEN,
INFO: NOCOLOR,
DEBUG: BLUE,
}