-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
88 lines (73 loc) · 2.15 KB
/
formatter.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package send
import (
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"github.com/tychoish/grip/message"
)
type withOptionImpl struct {
Sender
opts []message.Option
}
func WithOptionSender(s Sender, options ...message.Option) Sender {
return &withOptionImpl{Sender: s, opts: options}
}
func (s withOptionImpl) Send(m message.Composer) { m.SetOption(s.opts...); s.Sender.Send(m) }
const (
defaultFormatTmpl = "[p=%s]: %s"
callSiteTmpl = "[p=%s] [%s:%d]: %s"
)
// MakeJSONFormatter returns a MessageFormatter, that returns messages
// as the string form of a JSON document built using the Raw method of
// the Composer. Returns an error if there was a problem marshalling JSON.
func MakeJSONFormatter() MessageFormatter {
return func(m message.Composer) (string, error) {
out, err := json.Marshal(m.Raw())
if err != nil {
return "", err
}
return string(out), nil
}
}
// MakeDefaultFormatter returns a MessageFormatter that will produce a
// message in the following format:
//
// [p=<level>]: <message>
//
// It can never error.
func MakeDefaultFormatter() MessageFormatter {
return func(m message.Composer) (string, error) {
return fmt.Sprintf(defaultFormatTmpl, m.Priority(), m.String()), nil
}
}
// MakePlainFormatter returns a MessageFormatter that simply returns the
// string format of the log message.
func MakePlainFormatter() MessageFormatter {
return func(m message.Composer) (string, error) {
return m.String(), nil
}
}
// MakeCallSiteFormatter returns a MessageFormater that formats
// messages with the following format:
//
// [p=<level>] [<fileName>:<lineNumber>]: <message>
//
// It can never error.
func MakeCallSiteFormatter(depth int) MessageFormatter {
depth++
return func(m message.Composer) (string, error) {
file, line := callerInfo(depth)
return fmt.Sprintf(callSiteTmpl, m.Priority(), file, line, m), nil
}
}
func callerInfo(depth int) (string, int) {
// increase depth to account for callerInfo itself.
depth++
// get caller info.
_, file, line, _ := runtime.Caller(depth)
// get the directory and filename
dir, fileName := filepath.Split(file)
file = filepath.Join(filepath.Base(dir), fileName)
return file, line
}