-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
72 lines (59 loc) · 1.5 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
package sindri
import (
"bytes"
"context"
"fmt"
"os/exec"
"strings"
xio "github.com/frantjc/x/io"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"go.uber.org/zap"
)
// Logger is an alias to logr.Logger in case
// the logging library is desired to be swapped out.
type Logger = logr.Logger
// WithLogger returns a Context from the parent Context
// with the given Logger inside of it.
func WithLogger(ctx context.Context, log Logger) context.Context {
return logr.NewContext(ctx, log)
}
// LoggerFrom returns a Logger embedded within the given Context
// or a no-op Logger if no such Logger exists.
func LoggerFrom(ctx context.Context) Logger {
return logr.FromContextOrDiscard(ctx)
}
// NewLogger creates a new Logger.
func NewLogger() Logger {
zapLogger, err := zap.NewProduction(
zap.AddCallerSkip(1),
)
if err != nil {
panic(err)
}
return zapr.NewLogger(zapLogger)
}
var (
errStderr = fmt.Errorf("stderr")
)
// LogExec redirects a command's stdout and stderr
// to the given Logger.
func LogExec(log Logger, cmd *exec.Cmd) {
log = log.WithValues("bin", cmd.Path)
cmd.Stdout = xio.WriterFunc(func(b []byte) (int, error) {
for _, p := range bytes.Split(b, []byte("\n")) {
if len(p) > 0 {
log.Info(strings.TrimSpace(string(p)))
}
}
return len(b), nil
})
cmd.Stderr = xio.WriterFunc(func(b []byte) (int, error) {
for _, p := range bytes.Split(b, []byte("\n")) {
if len(p) > 0 {
log.Error(errStderr, strings.TrimSpace(string(p)))
}
}
return len(b), nil
})
}