-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger_config.go
102 lines (90 loc) · 2.32 KB
/
logger_config.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
package main
import (
"fmt"
"io"
"log/slog"
"os"
"github.com/Layr-Labs/eigensdk-go/logging"
"github.com/urfave/cli"
)
const (
pathFlagName = "log.path"
levelFlagName = "log.level"
formatFlagName = "log.format"
)
type LogFormat string
const (
JSONLogFormat LogFormat = "json"
TextLogFormat LogFormat = "text"
)
type LoggerConfig struct {
Format LogFormat
OutputWriter io.Writer
HandlerOpts slog.HandlerOptions
}
var loggerFlags = []cli.Flag{
cli.StringFlag{
Name: levelFlagName,
Usage: `The lowest log level that will be output. Accepted options are "debug", "info", "warn", "error"`,
Value: "info",
EnvVar: envVarPrefix + "LOG_LEVEL",
},
cli.StringFlag{
Name: pathFlagName,
Usage: "Path to file where logs will be written",
Value: "",
EnvVar: envVarPrefix + "LOG_PATH",
},
cli.StringFlag{
Name: formatFlagName,
Usage: "The format of the log file. Accepted options are 'json' and 'text'",
Value: "json",
EnvVar: envVarPrefix + "LOG_FORMAT",
},
}
func DefaultLoggerConfig() LoggerConfig {
return LoggerConfig{
Format: JSONLogFormat,
OutputWriter: os.Stdout,
HandlerOpts: slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
},
}
}
func ReadLoggerCLIConfig(ctx *cli.Context) (*LoggerConfig, error) {
cfg := DefaultLoggerConfig()
format := ctx.GlobalString(formatFlagName)
if format == "json" {
cfg.Format = JSONLogFormat
} else if format == "text" {
cfg.Format = TextLogFormat
} else {
return nil, fmt.Errorf("invalid log file format %s", format)
}
path := ctx.GlobalString(pathFlagName)
if path != "" {
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
cfg.OutputWriter = io.MultiWriter(os.Stdout, f)
}
logLevel := ctx.GlobalString(levelFlagName)
var level slog.Level
err := level.UnmarshalText([]byte(logLevel))
if err != nil {
panic("failed to parse log level " + logLevel)
}
cfg.HandlerOpts.Level = level
return &cfg, nil
}
func NewLogger(cfg LoggerConfig) (logging.Logger, error) {
if cfg.Format == JSONLogFormat {
return logging.NewSlogJsonLogger(cfg.OutputWriter, &cfg.HandlerOpts), nil
}
if cfg.Format == TextLogFormat {
return logging.NewSlogTextLogger(cfg.OutputWriter, &cfg.HandlerOpts), nil
}
return nil, fmt.Errorf("unknown log format: %s", cfg.Format)
}