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
package node
import (
"fmt"
"os"
"strings"
"github.com/ethereum/go-ethereum/log"
"golang.org/x/term"
)
type LogConfig struct {
Level string // Log level: trace, debug, info, warn, error, crit. Capitals are accepted too.
Color bool // Color the log output. Defaults to true if terminal is detected.
Format string // Format the log output. Supported formats: 'text', 'json'
}
func DefaultLogConfig() LogConfig {
return LogConfig{
Level: "info",
Format: "text",
Color: term.IsTerminal(int(os.Stdout.Fd())),
}
}
// Check verifes that the LogConfig is valid. Calls to `NewLogger` may fail if this
// returns an error.
func (cfg *LogConfig) Check() error {
switch cfg.Format {
case "json", "json-pretty", "terminal", "text":
default:
return fmt.Errorf("unrecognized log format: %s", cfg.Format)
}
level := strings.ToLower(cfg.Level) // ignore case
_, err := log.LvlFromString(level)
if err != nil {
return fmt.Errorf("unrecognized log level: %w", err)
}
return nil
}
// NewLogger creates a logger based on the supplied configuration
func (cfg *LogConfig) NewLogger() log.Logger {
handler := log.StreamHandler(os.Stdout, format(cfg.Format, cfg.Color))
handler = log.SyncHandler(handler)
log.LvlFilterHandler(level(cfg.Level), handler)
logger := log.New()
logger.SetHandler(handler)
return logger
}
// format turns a string and color into a structured Format object
func format(lf string, color bool) log.Format {
switch lf {
case "json":
return log.JSONFormat()
case "json-pretty":
return log.JSONFormatEx(true, true)
case "text", "terminal":
return log.TerminalFormat(color)
default:
panic("Failed to create `log.Format` from options")
}
}
// level parses the level string into an appropriate object
func level(s string) log.Lvl {
s = strings.ToLower(s) // ignore case
l, err := log.LvlFromString(s)
if err != nil {
panic(fmt.Sprintf("Could not parse log level: %v", err))
}
return l
}