-
Notifications
You must be signed in to change notification settings - Fork 8
/
logger.go
117 lines (94 loc) · 2.52 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package simplelog
import (
"bytes"
"fmt"
"io"
"github.com/spf13/pflag"
"namespacelabs.dev/foundation/internal/console/colors"
"namespacelabs.dev/foundation/internal/console/consolesink"
"namespacelabs.dev/foundation/std/tasks"
"namespacelabs.dev/foundation/std/tasks/idtypes"
)
var AlsoReportStartEvents = false
func SetupFlags(flags *pflag.FlagSet) {
flags.BoolVar(&AlsoReportStartEvents, "also_report_start_events", AlsoReportStartEvents,
"If set to true, we log a start event for each action, if --log_actions is also set.")
_ = flags.MarkHidden("also_report_start_events")
}
func NewSink(w io.Writer, maxLevel int) tasks.ActionSink {
return &logger{w, maxLevel}
}
type logger struct {
out io.Writer
maxLevel int // Only display actions at this level or below (all actions are still computed).
}
func (sl logger) shouldLog(ev tasks.EventData) bool {
// Don't emit logs for "compute.wait".
if ev.AnchorID != "" {
return false
}
return ev.Level <= sl.maxLevel
}
func (sl *logger) Waiting(ra *tasks.RunningAction) {
// Do nothing.
}
func (sl logger) write(b []byte) {
// Ignore errors
_, _ = sl.out.Write(b)
}
func (sl *logger) Started(ra *tasks.RunningAction) {
if !tasks.LogActions || !AlsoReportStartEvents {
return
}
if !sl.shouldLog(ra.Data) {
return
}
var b bytes.Buffer
fmt.Fprint(&b, "↦ ")
consolesink.LogAction(&b, colors.NoColors, ra.Data)
sl.write(b.Bytes())
}
func (sl *logger) Done(ra *tasks.RunningAction) {
if !tasks.LogActions {
return
}
if !sl.shouldLog(ra.Data) {
return
}
var b bytes.Buffer
if AlsoReportStartEvents {
if ra.Data.Err == nil {
fmt.Fprint(&b, "✔ ")
} else {
fmt.Fprint(&b, "✘ ")
}
}
consolesink.LogAction(&b, colors.NoColors, ra.Data)
sl.write(b.Bytes())
}
func (sl *logger) Instant(ev *tasks.EventData) {
if !tasks.LogActions {
return
}
if !sl.shouldLog(*ev) {
return
}
var b bytes.Buffer
if AlsoReportStartEvents {
// We use checkboxes here to distinguish Instant() vs Done()
if ev.Err == nil {
fmt.Fprint(&b, "☑ ")
} else {
fmt.Fprint(&b, "☒ ")
}
}
consolesink.LogAction(&b, colors.NoColors, *ev)
sl.write(b.Bytes())
}
func (sl *logger) AttachmentsUpdated(tasks.ActionID, *tasks.ResultData) { /* nothing to do */ }
func (sl *logger) Output(name, contentType string, outputType idtypes.CatOutputType) io.Writer {
return nil
}