Debian Codegraph @

pkg/sink/stdiosink/stdio.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package stdiosink
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "sort"
9 "strings"
10 "text/tabwriter"
11 "time"
12
13 "github.com/fatih/color"
14 "github.com/humanlogio/humanlog/internal/pkg/config"
15 "github.com/humanlogio/humanlog/internal/pkg/model"
•16 "github.com/humanlogio/humanlog/pkg/sink"
17 )
18
19 var (
20 eol = [...]byte{'\n'}
21 )
22
23 type Stdio struct {
24 w io.Writer
25 opts StdioOpts
26
27 lastRaw bool
28 lastLevel string
29 lastKVs map[string]string
30 }
31
32 type StdioOpts struct {
33 Keep map[string]struct{}
34 Skip map[string]struct{}
35 SkipUnchanged bool
36 SortLongest bool
37 TimeFormat string
38 TruncateLength int
39 Truncates bool
40
41 ColorFlag string
42 LightBg bool
43 Palette Palette
44 }
45
46 var DefaultStdioOpts = StdioOpts{
47
48 SkipUnchanged: true,
49 SortLongest: true,
50 TimeFormat: time.Stamp,
51 TruncateLength: 15,
52 Truncates: true,
53
54 ColorFlag: "auto",
55 LightBg: false,
56 Palette: DefaultPalette,
57 }
58
59 func StdioOptsFrom(cfg config.Config) (StdioOpts, []error) {
60 var errs []error
61 opts := DefaultStdioOpts
62 if cfg.Skip != nil {
63 opts.Skip = sliceToSet(cfg.Skip)
64 }
65 if cfg.Keep != nil {
66 opts.Keep = sliceToSet(cfg.Keep)
67 }
68 if cfg.SortLongest != nil {
69 opts.SortLongest = *cfg.SortLongest
70 }
71 if cfg.SkipUnchanged != nil {
72 opts.SkipUnchanged = *cfg.SkipUnchanged
73 }
74 if cfg.Truncates != nil {
75 opts.Truncates = *cfg.Truncates
76 }
77 if cfg.LightBg != nil {
78 opts.LightBg = *cfg.LightBg
79 }
80 if cfg.TruncateLength != nil {
81 opts.TruncateLength = *cfg.TruncateLength
82 }
83 if cfg.TimeFormat != nil {
84 opts.TimeFormat = *cfg.TimeFormat
85 }
86 if cfg.ColorMode != nil {
87 colorMode, err := config.GrokColorMode(*cfg.ColorMode)
88 if err != nil {
89 errs = append(errs, fmt.Errorf("invalid --color=%q: %v", *cfg.ColorMode, err))
90 }
91 switch colorMode {
92 case config.ColorModeOff:
93 color.NoColor = true
94 case config.ColorModeOn:
95 color.NoColor = false
96 default:
97 // 'Auto' default is applied as a global variable initializer function, so nothing
98 // to do here.
99 }
100 }
101 if cfg.Palette != nil {
102 pl, err := PaletteFrom(*cfg.Palette)
103 if err != nil {
104 errs = append(errs, fmt.Errorf("invalid palette, using default one: %v", err))
105 } else {
106 opts.Palette = *pl
107 }
108 }
109 return opts, errs
110 }
111
112 var _ sink.Sink = (*Stdio)(nil)
113
114 func NewStdio(w io.Writer, opts StdioOpts) *Stdio {
115 return &Stdio{
116 w: w,
117 opts: opts,
118 }
119 }
120
121 func (std *Stdio) Receive(ctx context.Context, ev *model.Event) error {
122 if ev.Structured == nil {
123 std.lastRaw = true
124 std.lastLevel = ""
125 std.lastKVs = nil
126 if _, err := std.w.Write(ev.Raw); err != nil {
127 return err
128 }
129 if _, err := std.w.Write(eol[:]); err != nil {
130 return err
131 }
132 return nil
133 }
134 data := ev.Structured
135
136 buf := bytes.NewBuffer(nil)
137 out := tabwriter.NewWriter(buf, 0, 1, 0, '\t', 0)
138
139 var (
140 msgColor *color.Color
141 msgAbsentColor *color.Color
142 )
143 if std.opts.LightBg {
144 msgColor = std.opts.Palette.MsgLightBgColor
145 msgAbsentColor = std.opts.Palette.MsgAbsentLightBgColor
146 } else {
147 msgColor = std.opts.Palette.MsgDarkBgColor
148 msgAbsentColor = std.opts.Palette.MsgAbsentDarkBgColor
149 }
150 var msg string
151 if data.Msg == "" {
152 msg = msgAbsentColor.Sprint("<no msg>")
153 } else {
154 msg = msgColor.Sprint(data.Msg)
155 }
156
157 lvl := strings.ToUpper(data.Level)[:imin(4, len(data.Level))]
158 var level string
159 switch strings.ToLower(data.Level) {
160 case "debug":
161 level = std.opts.Palette.DebugLevelColor.Sprint(lvl)
162 case "info":
163 level = std.opts.Palette.InfoLevelColor.Sprint(lvl)
164 case "warn", "warning":
165 level = std.opts.Palette.WarnLevelColor.Sprint(lvl)
166 case "error":
167 level = std.opts.Palette.ErrorLevelColor.Sprint(lvl)
168 case "fatal", "panic":
169 level = std.opts.Palette.FatalLevelColor.Sprint(lvl)
170 default:
171 level = std.opts.Palette.UnknownLevelColor.Sprint(lvl)
172 }
173
174 var timeColor *color.Color
175 if std.opts.LightBg {
176 timeColor = std.opts.Palette.TimeLightBgColor
177 } else {
178 timeColor = std.opts.Palette.TimeDarkBgColor
179 }
180
181 _, _ = fmt.Fprintf(out, "%s |%s| %s\t %s",
182 timeColor.Sprint(data.Time.Format(std.opts.TimeFormat)),
183 level,
184 msg,
185 strings.Join(std.joinKVs(data, "="), "\t "),
186 )
187
188 if err := out.Flush(); err != nil {
189 return err
190 }
191
192 buf.Write(eol[:])
193
194 if _, err := buf.WriteTo(std.w); err != nil {
195 return err
196 }
197
198 kvs := make(map[string]string, len(data.KVs))
199 for _, kv := range data.KVs {
200 kvs[kv.Key] = kv.Value
201 }
202 std.lastRaw = false
203 std.lastLevel = ev.Structured.Level
204 std.lastKVs = kvs
205 return nil
206 }
207
208 func (std *Stdio) joinKVs(data *model.Structured, sep string) []string {
209 wasSameLevel := std.lastLevel == data.Level
210 skipUnchanged := !std.lastRaw && std.opts.SkipUnchanged && wasSameLevel
211
212 kv := make([]string, 0, len(data.KVs))
213 for _, pair := range data.KVs {
214 k, v := pair.Key, pair.Value
215 if !std.opts.shouldShowKey(k) {
216 continue
217 }
218
219 if skipUnchanged {
220 if lastV, ok := std.lastKVs[k]; ok && lastV == v && !std.opts.shouldShowUnchanged(k) {
221 continue
222 }
223 }
224 kstr := std.opts.Palette.KeyColor.Sprint(k)
225
226 var vstr string
227 if std.opts.Truncates && len(v) > std.opts.TruncateLength {
228 vstr = v[:std.opts.TruncateLength] + "..."
229 } else {
230 vstr = v
231 }
232 vstr = std.opts.Palette.ValColor.Sprint(vstr)
233 kv = append(kv, kstr+sep+vstr)
234 }
235
236 sort.Strings(kv)
237
238 if std.opts.SortLongest {
239 sort.Stable(byLongest(kv))
240 }
241
242 return kv
243 }
244
245 func (opts *StdioOpts) shouldShowKey(key string) bool {
246 if len(opts.Keep) != 0 {
247 if _, keep := opts.Keep[key]; keep {
248 return true
249 }
250 }
251 if len(opts.Skip) != 0 {
252 if _, skip := opts.Skip[key]; skip {
253 return false
254 }
255 }
256 return true
257 }
258
259 func (opts *StdioOpts) shouldShowUnchanged(key string) bool {
260 if len(opts.Keep) != 0 {
261 if _, keep := opts.Keep[key]; keep {
262 return true
263 }
264 }
265 return false
266 }
267
268 type byLongest []string
269
270 func (s byLongest) Len() int { return len(s) }
271 func (s byLongest) Less(i, j int) bool { return len(s[i]) < len(s[j]) }
272 func (s byLongest) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
273
274 func imin(a, b int) int {
275 if a < b {
276 return a
277 }
278 return b
279 }
280
281 func sliceToSet(arr *[]string) map[string]struct{} {
282 if arr == nil {
283 return nil
284 }
285 out := make(map[string]struct{})
286 for _, key := range *arr {
287 out[key] = struct{}{}
288 }
289 return out
290 }