-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpog.go
More file actions
314 lines (267 loc) · 8.59 KB
/
pog.go
File metadata and controls
314 lines (267 loc) · 8.59 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Package pog provides a simple logger for Go with a terminal status indicator.
//
// Pog wraps the standard log package, adding colored log level indicators and a
// persistent status line that is redrawn at the bottom of the terminal.
package pog
import (
"fmt"
"io"
"log"
"os"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
// Pogger is a logger with a terminal status indicator. It wraps a [log.Logger]
// and adds leveled logging and a persistent status line.
type Pogger struct {
out io.Writer
logger *log.Logger
status Status
stopCh chan struct{}
stopOnce sync.Once
m sync.Mutex
initOnce sync.Once
exitHooks []func()
}
// NewPogger creates a new Pogger that writes to out. The prefix and flag
// arguments are passed to [log.New] for the underlying logger. A background
// goroutine is started to manage the status line; call [Pogger.Stop] to stop it.
func NewPogger(out io.Writer, prefix string, flag int) *Pogger {
pogger := Pogger{
out: out,
logger: log.New(out, prefix, flag),
stopCh: make(chan struct{}),
}
go pogger.loop()
return &pogger
}
// SetStatus sets the status displayed on the terminal status line.
func (p *Pogger) SetStatus(status Status) {
p.m.Lock()
p.status = status
p.m.Unlock()
}
// Debug logs a message with the debug level indicator [d].
func (p *Pogger) Debug(v ...any) {
a := []any{color.WhiteString("[d]") + " "}
a = append(a, v...)
p.logger.Print(a...)
}
// Debugln logs a message with the debug level indicator [d], followed by a newline.
func (p *Pogger) Debugln(v ...any) {
a := []any{color.WhiteString("[d]")}
a = append(a, v...)
p.logger.Println(a...)
}
// Debugf logs a formatted message with the debug level indicator [d].
func (p *Pogger) Debugf(format string, v ...any) {
p.logger.Printf(color.WhiteString("[d]")+" "+format, v...)
}
// Info logs a message with the info level indicator [i].
func (p *Pogger) Info(v ...any) {
a := []any{"[i] "}
a = append(a, v...)
p.logger.Print(a...)
}
// Infoln logs a message with the info level indicator [i], followed by a newline.
func (p *Pogger) Infoln(v ...any) {
a := []any{"[i]"}
a = append(a, v...)
p.logger.Println(a...)
}
// Infof logs a formatted message with the info level indicator [i].
func (p *Pogger) Infof(format string, v ...any) {
p.logger.Printf("[i] "+format, v...)
}
// Warn logs a message with the warn level indicator [w].
func (p *Pogger) Warn(v ...any) {
a := []any{color.YellowString("[w]") + " "}
a = append(a, v...)
p.logger.Print(a...)
}
// Warnln logs a message with the warn level indicator [w], followed by a newline.
func (p *Pogger) Warnln(v ...any) {
a := []any{color.YellowString("[w]")}
a = append(a, v...)
p.logger.Println(a...)
}
// Warnf logs a formatted message with the warn level indicator [w].
func (p *Pogger) Warnf(format string, v ...any) {
p.logger.Printf(color.YellowString("[w]")+" "+format, v...)
}
// Error logs a message with the error level indicator [E].
func (p *Pogger) Error(v ...any) {
a := []any{color.RedString("[E]") + " "}
a = append(a, v...)
p.logger.Print(a...)
}
// Errorln logs a message with the error level indicator [E], followed by a newline.
func (p *Pogger) Errorln(v ...any) {
a := []any{color.RedString("[E]")}
a = append(a, v...)
p.logger.Println(a...)
}
// Errorf logs a formatted message with the error level indicator [E].
func (p *Pogger) Errorf(format string, v ...any) {
p.logger.Printf(color.RedString("[E]")+" "+format, v...)
}
// Fatal logs a message with the error level indicator [E] and then calls
// os.Exit(1), running any registered exit hooks first.
func (p *Pogger) Fatal(v ...any) {
p.Error(v...)
p.exit(1)
}
// Fatalln logs a message with the error level indicator [E] followed by a
// newline and then calls os.Exit(1), running any registered exit hooks first.
func (p *Pogger) Fatalln(v ...any) {
p.Errorln(v...)
p.exit(1)
}
// Fatalf logs a formatted message with the error level indicator [E] and then
// calls os.Exit(1), running any registered exit hooks first.
func (p *Pogger) Fatalf(format string, v ...any) {
p.Errorf(format, v...)
p.exit(1)
}
// AddExitHook registers a function to be called before os.Exit when a Fatal
// method is invoked.
func (p *Pogger) AddExitHook(fn func()) {
p.m.Lock()
p.exitHooks = append(p.exitHooks, fn)
p.m.Unlock()
}
// Stop stops the background goroutine that manages the status line. It is safe
// to call multiple times.
func (p *Pogger) Stop() {
p.stopOnce.Do(func() {
close(p.stopCh)
})
}
func (p *Pogger) prefixLen() int {
n := len(p.logger.Prefix())
flags := p.logger.Flags()
if flags&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 {
if flags&log.Ldate != 0 {
n += len("2006/01/02 ")
}
if flags&(log.Ltime|log.Lmicroseconds) != 0 {
if flags&log.Lmicroseconds != 0 {
n += len("15:04:05.000000 ")
} else {
n += len("15:04:05 ")
}
}
}
return n
}
func (p *Pogger) loop() {
cur := ""
pad := ""
if n := p.prefixLen(); n > 0 {
pad = strings.Repeat(" ", n)
}
ticker := time.NewTicker(125 * time.Millisecond)
defer ticker.Stop()
L:
for i := 0; ; i = (i + 1) % 10 {
var s string
p.m.Lock()
b := []byte{' '}
if p.status != nil {
if i < 5 || !p.status.Throb() {
b[0] = p.status.Icon()
}
s = "[" + string(b) + "]"
if color := p.status.Color(); color != nil {
s = color.Sprint(s)
}
s += " " + p.status.Text()
}
p.m.Unlock()
if s != cur {
fmt.Fprintf(p.out, "\033[2K\r%s%s\r", pad, s)
cur = s
}
select {
case <-p.stopCh:
break L
case <-ticker.C:
}
}
}
func (p *Pogger) exit(code int) {
p.Stop()
p.m.Lock()
hooks := make([]func(), len(p.exitHooks))
copy(hooks, p.exitHooks)
p.m.Unlock()
for _, fn := range hooks {
fn()
}
os.Exit(code)
}
// Status represents the state displayed on the terminal status line.
type Status interface {
// Icon returns the character shown inside the status indicator brackets.
Icon() byte
// Text returns the text displayed next to the status indicator.
Text() string
// Color returns the color used to render the status indicator, or nil for
// no color.
Color() *color.Color
// Throb returns whether the status indicator should animate by toggling the
// icon on and off.
Throb() bool
}
var (
defaultPogger *Pogger
)
// InitDefault initializes the default Pogger using the settings from
// [log.Default]. It must be called before using the package-level logging
// functions.
func InitDefault() {
defaultPogger = NewPogger(log.Default().Writer(), log.Default().Prefix(), log.Default().Flags())
}
// Default returns the default Pogger. It returns nil if [InitDefault] has not
// been called.
func Default() *Pogger {
return defaultPogger
}
// SetStatus sets the status on the default Pogger.
func SetStatus(status Status) { defaultPogger.SetStatus(status) }
// Debug calls [Pogger.Debug] on the default Pogger.
func Debug(v ...any) { defaultPogger.Debug(v...) }
// Debugln calls [Pogger.Debugln] on the default Pogger.
func Debugln(v ...any) { defaultPogger.Debugln(v...) }
// Debugf calls [Pogger.Debugf] on the default Pogger.
func Debugf(format string, v ...any) { defaultPogger.Debugf(format, v...) }
// Info calls [Pogger.Info] on the default Pogger.
func Info(v ...any) { defaultPogger.Info(v...) }
// Infoln calls [Pogger.Infoln] on the default Pogger.
func Infoln(v ...any) { defaultPogger.Infoln(v...) }
// Infof calls [Pogger.Infof] on the default Pogger.
func Infof(format string, v ...any) { defaultPogger.Infof(format, v...) }
// Warn calls [Pogger.Warn] on the default Pogger.
func Warn(v ...any) { defaultPogger.Warn(v...) }
// Warnln calls [Pogger.Warnln] on the default Pogger.
func Warnln(v ...any) { defaultPogger.Warnln(v...) }
// Warnf calls [Pogger.Warnf] on the default Pogger.
func Warnf(format string, v ...any) { defaultPogger.Warnf(format, v...) }
// Error calls [Pogger.Error] on the default Pogger.
func Error(v ...any) { defaultPogger.Error(v...) }
// Errorln calls [Pogger.Errorln] on the default Pogger.
func Errorln(v ...any) { defaultPogger.Errorln(v...) }
// Errorf calls [Pogger.Errorf] on the default Pogger.
func Errorf(format string, v ...any) { defaultPogger.Errorf(format, v...) }
// Fatal calls [Pogger.Fatal] on the default Pogger.
func Fatal(v ...any) { defaultPogger.Fatal(v...) }
// Fatalln calls [Pogger.Fatalln] on the default Pogger.
func Fatalln(v ...any) { defaultPogger.Fatalln(v...) }
// Fatalf calls [Pogger.Fatalf] on the default Pogger.
func Fatalf(format string, v ...any) { defaultPogger.Fatalf(format, v...) }
// Stop calls [Pogger.Stop] on the default Pogger.
func Stop() { defaultPogger.Stop() }
// AddExitHook calls [Pogger.AddExitHook] on the default Pogger.
func AddExitHook(fn func()) { defaultPogger.AddExitHook(fn) }