/
logging.go
218 lines (191 loc) · 6.86 KB
/
logging.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Contains various utility functions related to logging.
package cli
import (
"bytes"
"container/list"
"fmt"
"io"
"os"
"path"
"regexp"
"strings"
"sync"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/op/go-logging.v1"
)
var log = logging.MustGetLogger("cli")
// StdErrIsATerminal is true if the process' stderr is an interactive TTY.
var StdErrIsATerminal = terminal.IsTerminal(int(os.Stderr.Fd()))
// StdOutIsATerminal is true if the process' stdout is an interactive TTY.
var StdOutIsATerminal = terminal.IsTerminal(int(os.Stdout.Fd()))
// StripAnsi is a regex to find & replace ANSI console escape sequences.
var StripAnsi = regexp.MustCompile("\x1b[^m]+m")
// LogLevel is the current verbosity level that is set.
// N.B. Setting this does *not* alter it. Use InitLogging for that.
var LogLevel = logging.WARNING
var fileLogLevel = logging.WARNING
var fileBackend *logging.LogBackend
type logFileWriter struct {
file io.Writer
}
func (writer logFileWriter) Write(p []byte) (n int, err error) {
return writer.file.Write(StripAnsi.ReplaceAllLiteral(p, []byte{}))
}
// translateLogLevel translates our verbosity flags to logging levels.
func translateLogLevel(verbosity int) logging.Level {
if verbosity <= 0 {
return logging.ERROR
} else if verbosity == 1 {
return logging.WARNING
} else if verbosity == 2 {
return logging.NOTICE
} else if verbosity == 3 {
return logging.INFO
} else {
return logging.DEBUG
}
}
// InitLogging initialises logging backends.
func InitLogging(verbosity int) {
LogLevel = translateLogLevel(verbosity)
logging.SetFormatter(logFormatter())
setLogBackend(logging.NewLogBackend(os.Stderr, "", 0))
}
// InitFileLogging initialises an optional logging backend to a file.
func InitFileLogging(logFile string, logFileLevel int) {
fileLogLevel = translateLogLevel(logFileLevel)
if err := os.MkdirAll(path.Dir(logFile), os.ModeDir|0775); err != nil {
log.Fatalf("Error creating log file directory: %s", err)
}
if file, err := os.Create(logFile); err != nil {
log.Fatalf("Error opening log file: %s", err)
} else {
fileBackend = logging.NewLogBackend(logFileWriter{file: file}, "", 0)
setLogBackend(logging.NewLogBackend(os.Stderr, "", 0))
}
}
func logFormatter() logging.Formatter {
formatStr := "%{time:15:04:05.000} %{level:7s}: %{message}"
if StdErrIsATerminal {
formatStr = "%{color}" + formatStr + "%{color:reset}"
}
return logging.MustStringFormatter(formatStr)
}
func setLogBackend(backend logging.Backend) {
backendLeveled := logging.AddModuleLevel(backend)
backendLeveled.SetLevel(LogLevel, "")
if fileBackend == nil {
logging.SetBackend(backendLeveled)
} else {
fileBackendLeveled := logging.AddModuleLevel(fileBackend)
fileBackendLeveled.SetLevel(fileLogLevel, "")
logging.SetBackend(backendLeveled, fileBackendLeveled)
}
}
type logBackendFacade struct {
realBackend *LogBackend // To work around the logging interface requiring us to pass by value.
}
func (backend logBackendFacade) Log(level logging.Level, calldepth int, rec *logging.Record) error {
var b bytes.Buffer
backend.realBackend.Formatter.Format(calldepth, rec, &b)
if rec.Level <= logging.CRITICAL {
fmt.Print(b.String()) // Don't capture critical messages, just die immediately.
os.Exit(1)
}
backend.realBackend.Lock()
defer backend.realBackend.Unlock()
backend.realBackend.LogMessages.PushBack(strings.TrimSpace(b.String()))
backend.realBackend.RecalcLines()
return nil
}
// LogBackend is the backend we use for logging during the interactive console display.
type LogBackend struct {
sync.Mutex // Protects access to LogMessages
Rows, Cols, MaxRecords, InteractiveRows, MaxInteractiveRows, maxLines int
Output []string
LogMessages *list.List
Formatter logging.Formatter // TODO(pebers): seems a bit weird that we have to have this here, but it doesn't
} // seem to be possible to retrieve the formatter from outside the package?
// RecalcLines recalculates how many lines we have available, typically in response to the window size changing
func (backend *LogBackend) RecalcLines() {
for backend.LogMessages.Len() >= backend.MaxRecords {
backend.LogMessages.Remove(backend.LogMessages.Front())
}
backend.maxLines = backend.Rows - backend.InteractiveRows - 1
if backend.maxLines > 15 {
backend.maxLines = 15 // Cap it here so we don't log too much
} else if backend.maxLines <= 0 {
backend.maxLines = 1 // Set a minimum so we don't have negative indices later.
}
backend.Output = backend.calcOutput()
backend.MaxInteractiveRows = backend.Rows - len(backend.Output) - 1
}
// NewLogBackend constructs a new logging backend.
func NewLogBackend(interactiveRows int) *LogBackend {
return &LogBackend{
InteractiveRows: interactiveRows,
MaxRecords: 10,
LogMessages: list.New(),
Formatter: logFormatter(),
}
}
func (backend *LogBackend) calcOutput() []string {
ret := []string{}
for e := backend.LogMessages.Back(); e != nil; e = e.Prev() {
new := backend.lineWrap(e.Value.(string))
if len(ret)+len(new) <= backend.maxLines {
ret = append(ret, new...)
}
}
if len(ret) > 0 {
ret = append(ret, "Messages:")
}
return reverse(ret)
}
// SetActive sets this backend as the currently active log backend.
func (backend *LogBackend) SetActive() {
setLogBackend(logBackendFacade{backend})
}
// Deactivate removes this backend as the currently active log backend.
func (backend *LogBackend) Deactivate() {
setLogBackend(logging.NewLogBackend(os.Stderr, "", 0))
}
// Wraps a string across multiple lines. Returned slice is reversed.
func (backend *LogBackend) lineWrap(msg string) []string {
lines := strings.Split(msg, "\n")
wrappedLines := make([]string, 0, len(lines))
for _, line := range lines {
for i := 0; i < len(line); {
split := i + findSplit(line[i:], backend.Cols)
wrappedLines = append(wrappedLines, line[i:split])
i = split
}
}
if len(wrappedLines) > backend.maxLines {
return reverse(wrappedLines[:backend.maxLines])
}
return reverse(wrappedLines)
}
func reverse(s []string) []string {
if len(s) > 1 {
r := []string{}
for i := len(s) - 1; i >= 0; i-- {
r = append(r, s[i])
}
return r
}
return s
}
// Tries to find an appropriate point to word wrap line, taking shell escape codes into account.
// (Note that because the escape codes are not visible, we can run past the max length for one of them)
func findSplit(line string, guess int) int {
if guess >= len(line) {
return len(line)
}
r := regexp.MustCompilePOSIX(fmt.Sprintf(".{%d,%d}(\\x1b[^m]+m)?", guess/2, guess))
m := r.FindStringIndex(line)
if m != nil {
return m[1] // second element in slice is the end index
}
return guess // Dunno what to do at this point. It's probably unlikely to happen often though.
}