-
Notifications
You must be signed in to change notification settings - Fork 232
/
logger.go
77 lines (68 loc) · 2.04 KB
/
logger.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
package logger
import (
"encoding/json"
"log"
"os"
)
// Logger wraps a few log.Logger instances in private fields.
// They are accessible via their respective methods.
type Logger struct {
debug *log.Logger
info *log.Logger
error *log.Logger
verbose bool
}
// NewLogger returns a reference to a Logger.
// We usually call this when initializing cmd.Logger.
// Later we pass this to client.NewClient so it can also log.
// By default debug and error go to os.Stderr, and info goes to os.Stdout
func NewLogger(verbose bool) *Logger {
result := &Logger{
log.New(os.Stderr, "", 0),
log.New(os.Stdout, "", 0),
log.New(os.Stderr, "", 0),
verbose,
}
result.Debug("Verbose Logging: %t", verbose)
return result
}
// Debug prints a formatted message to stderr only if verbose is set.
// Consider these messages useful for developers of the CLI.
// This method wraps log.Logger.Printf
func (l *Logger) Debug(format string, args ...interface{}) {
if l.verbose {
l.debug.Printf(format, args...)
}
}
// Info prints all args to os.Stdout
// It's commonly used for messages we want to show the user.
// This method wraps log.Logger.Print
func (l *Logger) Info(args ...interface{}) {
l.info.Print(args...)
}
// Infoln prints all args to os.Stdout followed by a newline.
// This method wraps log.Logger.Println
func (l *Logger) Infoln(args ...interface{}) {
l.info.Println(args...)
}
// Infof prints a formatted message to stdout
// This method wraps log.Logger.Printf
func (l *Logger) Infof(format string, args ...interface{}) {
l.info.Printf(format, args...)
}
// Error prints a message and the given error's message to os.Stderr
// This method wraps log.Logger.Print
func (l *Logger) Error(msg string, err error) {
if err != nil {
l.error.Print(msg, err.Error())
}
}
// Prettyify accepts a map of data and pretty prints it.
// It's using json.MarshalIndent and printing with log.Logger.Infoln
func (l *Logger) Prettyify(data interface{}) {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
l.error.Fatalln(err)
}
l.Infoln(string(bytes))
}