-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
53 lines (45 loc) · 1.2 KB
/
cli.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
package log
import (
"fmt"
"os"
"github.com/pkg/errors"
"github.com/rackorbit/log/encoder"
)
// Flags are CLI flags for use with [kong](https://github.com/alecthomas/kong)
type Flags struct {
Encoder string `enum:"console,json,logfmt" default:"logfmt"`
Level string `enum:"debug,info,warn,error,panic,fatal" default:"info"`
}
// RegisterFromFlags creates and registers a new logger using CLI flags.
func RegisterFromFlags(f Flags) (func(), error) {
level, ok := Levels[f.Level]
if !ok {
return nil, fmt.Errorf("log: unknown log level: \"%s\"", f.Level)
}
var e encoder.Encoder
switch f.Encoder {
case "console":
e = &encoder.Console{}
case "json":
e = &encoder.JSON{}
case "logfmt":
e = &encoder.Logfmt{}
default:
return nil, fmt.Errorf("log: unknown log encoder: \"%s\"", f.Encoder)
}
if err := e.Provision(); err != nil {
return nil, errors.Wrap(err, "log: failed to provision encoder")
}
l, err := New(&Config{
Encoder: e,
Level: level,
Output: os.Stderr,
})
if err != nil {
return nil, errors.Wrap(err, "log: failed to configure logger")
}
if err := Register(l); err != nil {
return nil, errors.Wrap(err, "log: failed to register logger")
}
return Sync, nil
}