-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzerolog.go
More file actions
771 lines (686 loc) · 23.2 KB
/
Copy pathzerolog.go
File metadata and controls
771 lines (686 loc) · 23.2 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// Package zerolog provides opinionated configuration of the [zerolog] package.
//
// For details on what all is configured and initialized see package's README.
//
// [zerolog]: https://github.com/rs/zerolog
package zerolog
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
stdlog "log"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/alecthomas/kong"
"github.com/felixge/httpsnoop"
"github.com/goccy/go-yaml"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gitlab.com/tozd/go/errors"
"gitlab.com/tozd/go/x"
)
const (
fileMode = 0o600
)
// Copied from zerolog/console.go.
const (
colorRed = iota + 31
colorBold = 1
)
// Defaults to be used with [Kong]
// initialization for LoggingConfig struct:
//
// kong.Vars{
// "defaultLoggingConsoleType": DefaultConsoleType,
// "defaultLoggingConsoleLevel": DefaultConsoleLevel,
// "defaultLoggingFileLevel": DefaultFileLevel,
// "defaultLoggingMainLevel": DefaultMainLevel,
// "defaultLoggingContextLevel": DefaultContextLevel,
// "defaultLoggingContextConditionalLevel": DefaultContextConditionalLevel,
// "defaultLoggingContextTriggerLevel": DefaultContextTriggerLevel,
// }
//
// [Kong]: https://github.com/alecthomas/kong
const (
DefaultConsoleType = "color"
DefaultConsoleLevel = "debug"
DefaultFileLevel = "debug"
DefaultMainLevel = "info"
DefaultContextLevel = "debug"
DefaultContextConditionalLevel = "debug"
DefaultContextTriggerLevel = "error"
)
// TimeFieldFormat is the format for timestamps in log entries.
const TimeFieldFormat = "2006-01-02T15:04:05.000Z07:00"
// Console is configuration of logging log entries to the console (stdout by default).
//
// Type can be the following values: color (human-friendly formatted and colorized),
// nocolor (just human-friendly formatted), json, disable (do not log to the console).
//
// Level can be trace, debug, info, warn, and error.
//
//nolint:lll
type Console struct {
Type string `default:"${defaultLoggingConsoleType}" enum:"color,nocolor,json,disable" help:"Type of console logging." json:"type" placeholder:"TYPE" yaml:"type"`
Level zerolog.Level `default:"${defaultLoggingConsoleLevel}" enum:"trace,debug,info,warn,error" help:"Filter out all log entries below the level." json:"level" placeholder:"LEVEL" yaml:"level"`
// Used primarily for testing.
Output io.Writer `json:"-" kong:"-" yaml:"-"`
}
// UnmarshalYAML implements yaml.BytesUnmarshaler.
func (c *Console) UnmarshalYAML(b []byte) error {
var tmp struct {
Type *string `yaml:"type"`
Level *string `yaml:"level"`
}
err := yaml.NewDecoder(bytes.NewReader(b), yaml.DisallowUnknownField()).Decode(&tmp)
if errors.Is(err, io.EOF) { //nolint:revive
// Nothing.
} else if err != nil {
return errors.WithStack(err)
}
if tmp.Level != nil {
level, err := zerolog.ParseLevel(*tmp.Level)
if err != nil {
return errors.WithStack(err)
}
c.Level = level
}
if tmp.Type != nil {
c.Type = *tmp.Type
}
return nil
}
// UnmarshalJSON implements json.Unmarshaler interface for Console.
func (c *Console) UnmarshalJSON(b []byte) error {
var tmp struct {
Type *string `json:"type"`
Level *string `json:"level"`
}
errE := x.UnmarshalWithoutUnknownFields(b, &tmp)
if errE != nil {
return errE
}
if tmp.Level != nil {
level, err := zerolog.ParseLevel(*tmp.Level)
if err != nil {
return errors.WithStack(err)
}
c.Level = level
}
if tmp.Type != nil {
c.Type = *tmp.Type
}
return nil
}
// File is configuration of logging log entries as JSON by appending them to a file at path.
//
// Level can be trace, debug, info, warn, and error.
//
//nolint:lll
type File struct {
Path string ` help:"Append log entries to a file (as well)." json:"path" placeholder:"PATH" type:"path" yaml:"path"`
Level zerolog.Level `default:"${defaultLoggingFileLevel}" enum:"trace,debug,info,warn,error" help:"Filter out all log entries below the level." json:"level" placeholder:"LEVEL" yaml:"level"`
}
// UnmarshalYAML implements yaml.BytesUnmarshaler.
func (f *File) UnmarshalYAML(b []byte) error {
var tmp struct {
Path *string `yaml:"path"`
Level *string `yaml:"level"`
}
err := yaml.NewDecoder(bytes.NewReader(b), yaml.DisallowUnknownField()).Decode(&tmp)
if errors.Is(err, io.EOF) { //nolint:revive
// Nothing.
} else if err != nil {
return errors.WithStack(err)
}
if tmp.Level != nil {
level, err := zerolog.ParseLevel(*tmp.Level)
if err != nil {
return errors.WithStack(err)
}
f.Level = level
}
if tmp.Path != nil {
f.Path = *tmp.Path
}
return nil
}
// UnmarshalJSON implements json.Unmarshaler interface for File.
func (f *File) UnmarshalJSON(b []byte) error {
var tmp struct {
Path *string `json:"path"`
Level *string `json:"level"`
}
errE := x.UnmarshalWithoutUnknownFields(b, &tmp)
if errE != nil {
return errE
}
if tmp.Level != nil {
level, err := zerolog.ParseLevel(*tmp.Level)
if err != nil {
return errors.WithStack(err)
}
f.Level = level
}
if tmp.Path != nil {
f.Path = *tmp.Path
}
return nil
}
// Main is configuration of the main logger.
//
// Level can be trace, debug, info, warn, and error.
// Level can be also disabled to disable main logger.
//
//nolint:lll
type Main struct {
Level zerolog.Level `default:"${defaultLoggingMainLevel}" enum:"trace,debug,info,warn,error,disabled" env:"LOGGING_MAIN_LEVEL" help:"Log entries at the level or higher." json:"level" placeholder:"LEVEL" short:"l" yaml:"level"`
}
// UnmarshalYAML implements yaml.BytesUnmarshaler.
func (m *Main) UnmarshalYAML(b []byte) error {
var tmp struct {
Level string `yaml:"level"`
}
err := yaml.NewDecoder(bytes.NewReader(b), yaml.DisallowUnknownField()).Decode(&tmp)
if errors.Is(err, io.EOF) { //nolint:revive
// Nothing.
} else if err != nil {
return errors.WithStack(err)
}
level, err := zerolog.ParseLevel(tmp.Level)
if err != nil {
return errors.WithStack(err)
}
m.Level = level
return nil
}
// UnmarshalJSON implements json.Unmarshaler interface for Main.
func (m *Main) UnmarshalJSON(b []byte) error {
var tmp struct {
Level string `json:"level"`
}
errE := x.UnmarshalWithoutUnknownFields(b, &tmp)
if errE != nil {
return errE
}
level, err := zerolog.ParseLevel(tmp.Level)
if err != nil {
return errors.WithStack(err)
}
m.Level = level
return nil
}
// Context is configuration of the context logger.
//
// Levels can be trace, debug, info, warn, and error.
// Level can be also disabled to disable context logger.
//
// It supports buffering log lines at the ConditionalLevel or below until triggered by a log
// entry at the TriggerLevel or higher. To disable this behavior, set Level and TriggerLevel
// to the same level.
//
//nolint:lll
type Context struct {
Level zerolog.Level `default:"${defaultLoggingContextLevel}" enum:"trace,debug,info,warn,error,disabled" help:"Log entries at the level or higher." json:"level" placeholder:"LEVEL" yaml:"level"`
ConditionalLevel zerolog.Level `default:"${defaultLoggingContextConditionalLevel}" enum:"trace,debug,info,warn,error" help:"Buffer log entries at the level and below until triggered." json:"conditionalLevel" name:"conditional" placeholder:"LEVEL" yaml:"conditionalLevel"`
TriggerLevel zerolog.Level `default:"${defaultLoggingContextTriggerLevel}" enum:"trace,debug,info,warn,error" help:"A log entry at the level or higher triggers." json:"triggerLevel" name:"trigger" placeholder:"LEVEL" yaml:"triggerLevel"`
}
// UnmarshalYAML implements yaml.BytesUnmarshaler.
func (c *Context) UnmarshalYAML(b []byte) error {
var tmp struct {
Level string `yaml:"level"`
ConditionalLevel string `yaml:"conditionalLevel"`
TriggerLevel string `yaml:"triggerLevel"`
}
err := yaml.NewDecoder(bytes.NewReader(b), yaml.DisallowUnknownField()).Decode(&tmp)
if errors.Is(err, io.EOF) { //nolint:revive
// Nothing.
} else if err != nil {
return errors.WithStack(err)
}
level, err := zerolog.ParseLevel(tmp.Level)
if err != nil {
return errors.WithStack(err)
}
conditionalLevel, err := zerolog.ParseLevel(tmp.ConditionalLevel)
if err != nil {
return errors.WithStack(err)
}
triggerLevel, err := zerolog.ParseLevel(tmp.TriggerLevel)
if err != nil {
return errors.WithStack(err)
}
c.Level = level
c.ConditionalLevel = conditionalLevel
c.TriggerLevel = triggerLevel
return nil
}
// UnmarshalJSON implements json.Unmarshaler interface for Context.
func (c *Context) UnmarshalJSON(b []byte) error {
var tmp struct {
Level string `json:"level"`
ConditionalLevel string `json:"conditionalLevel"`
TriggerLevel string `json:"triggerLevel"`
}
errE := x.UnmarshalWithoutUnknownFields(b, &tmp)
if errE != nil {
return errE
}
level, err := zerolog.ParseLevel(tmp.Level)
if err != nil {
return errors.WithStack(err)
}
conditionalLevel, err := zerolog.ParseLevel(tmp.ConditionalLevel)
if err != nil {
return errors.WithStack(err)
}
triggerLevel, err := zerolog.ParseLevel(tmp.TriggerLevel)
if err != nil {
return errors.WithStack(err)
}
c.Level = level
c.ConditionalLevel = conditionalLevel
c.TriggerLevel = triggerLevel
return nil
}
// Logging is configuration for console and file logging.
type Logging struct {
Console Console `embed:"" json:"console" prefix:"console." yaml:"console"`
File File `embed:"" json:"file" prefix:"file." yaml:"file"`
Main Main `embed:"" json:"main" prefix:"main." yaml:"main"`
Context Context `embed:"" json:"context" prefix:"context." yaml:"context"`
}
// WithContextFunc adds a logger to a context. It returns the new context, a function to close the
// logger (discarding any buffered entries), and a function to flush (trigger) any buffered entries.
type WithContextFunc = func(context.Context) (context.Context, func(), func())
// LoggingConfig struct can be provided embedded inside the config argument to
// function New and function New returns the logger in its Logger field and
// sets its WithContext field.
type LoggingConfig struct {
Logger zerolog.Logger ` json:"-" kong:"-" yaml:"-"`
WithContext WithContextFunc ` json:"-" kong:"-" yaml:"-"`
Logging Logging `embed:"" json:"logging" prefix:"logging." yaml:"logging"`
}
// GetLoggingConfig is used to return the embedded LoggingConfig.
func (l *LoggingConfig) GetLoggingConfig() *LoggingConfig {
return l
}
// We have to define a method and an interface to be able to access embedded LoggingConfig.
// See: https://github.com/golang/go/issues/51259
type hasLoggingConfig interface {
GetLoggingConfig() *LoggingConfig
}
// Copied from zerolog/console.go.
func needsQuote(s string) bool {
for i := range s {
if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' {
return true
}
}
return false
}
// Copied from zerolog/console.go.
func colorize(s interface{}, c int, disabled bool) string {
e := os.Getenv("NO_COLOR")
if e != "" || c == 0 {
disabled = true
}
if disabled {
return fmt.Sprintf("%s", s)
}
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s)
}
// formatError formats errors which have been marshaled into JSON object
// using gitlab.com/tozd/go/errors's Formatter.
//
// It extracts just the error message from error's JSON.
// Stack trace is written out separately in formatExtra.
func formatError(noColor bool) zerolog.Formatter {
return func(i interface{}) string {
j, ok := i.([]byte)
if !ok {
// Default zerolog's format error.
return colorize(colorize(fmt.Sprintf("%s", i), colorBold, noColor), colorRed, noColor)
}
err, errE := errors.UnmarshalJSON(j)
if errE != nil {
return colorize(colorize(fmt.Sprintf("[error: %s] %s", errE.Error(), i), colorBold, noColor), colorRed, noColor)
}
msg := err.Error()
if needsQuote(msg) {
msg = strconv.Quote(msg)
}
return colorize(colorize(msg, colorBold, noColor), colorRed, noColor)
}
}
// formatExtra extracts details from the error (it the error exists)
// and formats them after the current log line in the buffer.
//
// On error and above levels it also formats error's stack trace
// and recurses into joined and cause errors.
//
// The error message itself is extracted in formatError.
//
// The error should have been marshaled into JSON object using
// gitlab.com/tozd/go/errors's Formatter.
func formatExtra(noColor bool) func(map[string]interface{}, *bytes.Buffer) error {
return func(event map[string]interface{}, buf *bytes.Buffer) error {
eData, ok := event[zerolog.ErrorFieldName]
if !ok {
return nil
}
eJSON, errE := x.Marshal(eData)
if errE != nil {
return errE
}
if !bytes.HasPrefix(eJSON, []byte(`{`)) {
// The error field is not a structured JSON object. Skip extra formatting.
return nil
}
if event[zerolog.LevelFieldName] == nil {
return nil
}
l, ok := event[zerolog.LevelFieldName].(string)
if !ok {
return nil
}
level, err := zerolog.ParseLevel(l)
if err != nil {
errE = errors.WithStack(err)
errors.Details(errE)["level"] = l
return errE
}
e, errE := errors.UnmarshalJSON(eJSON)
if errE != nil {
errors.Details(errE)["json"] = string(eJSON)
return errE
}
formatter := errors.Formatter{
Error: e,
GetMessage: func(err error) string {
// We want error messages to be bold, recursively.
return colorize(err.Error(), colorBold, noColor)
},
}
format := "%#v"
if level >= zerolog.ErrorLevel {
format = "% -+#.1v"
}
// " " if the message format makes sure that the string ends with a newline.
message := fmt.Sprintf("% v", formatter)
full := fmt.Sprintf(format, formatter)
// Message has already been included in formatError.
full = strings.TrimPrefix(full, message)
if len(full) == 0 {
return nil
}
// Zerolog always adds a newline at the end.
// So we add one ourselves now and remove one from "full".
buf.WriteString("\n")
full = strings.TrimSuffix(full, "\n")
lines := strings.Split(full, "\n")
for i, line := range lines {
if len(line) > 0 {
buf.WriteString(colorize(line, colorRed, noColor))
}
if i < len(lines)-1 {
// We do not write a newline for the last line.
// Zerolog always adds a newline at the end.
buf.WriteString("\n")
}
}
return nil
}
}
// newConsoleWriter creates and initializes a new ConsoleWriter with 24-hour time
// format and formatting of errors which have been marshaled into JSON object
// using gitlab.com/tozd/go/errors's Formatter.
func newConsoleWriter(noColor bool, output io.Writer) *zerolog.ConsoleWriter {
w := zerolog.NewConsoleWriter()
w.Out = output
w.NoColor = noColor
w.TimeFormat = "15:04"
w.FormatErrFieldValue = formatError(w.NoColor)
w.FormatExtra = formatExtra(w.NoColor)
return &w
}
// ErrorMarshalFunc marshals errors into JSON as an object and not a string
// using gitlab.com/tozd/go/errors's Formatter.
func ErrorMarshalFunc(e error) interface{} {
if e == nil {
return nil
}
j, err := x.MarshalWithoutEscapeHTML(errors.Formatter{Error: e})
if err != nil {
fmt.Fprintf(os.Stderr, `zerolog: marshaling error "%s" into JSON failed: % -+#.1v`, e.Error(), err)
}
return json.RawMessage(j)
}
// New configures and initializes zerolog and Go's standard log package for logging.
//
// New expects configuration embedded inside config as a LoggingConfig struct
// and returns the logger in its Logger field and sets its WithContext field.
// LoggingConfig can be initially populated with configuration using [Kong].
//
// Returned file handle belongs to the file to which log entries are appended (if file
// logging is enabled in configuration). Closing it is caller's responsibility.
//
// For details on what all is configured and initialized see package's README.
//
// [Kong]: https://github.com/alecthomas/kong
func New[LoggingConfigT hasLoggingConfig](config LoggingConfigT) (*os.File, errors.E) {
loggingConfig := config.GetLoggingConfig()
minOutputLevel := zerolog.Disabled
writers := []io.Writer{}
output := loggingConfig.Logging.Console.Output
if output == nil {
output = os.Stdout
}
var file *os.File
switch loggingConfig.Logging.Console.Type {
case "color", "nocolor":
w := newConsoleWriter(loggingConfig.Logging.Console.Type == "nocolor", output)
writers = append(writers, &zerolog.FilteredLevelWriter{
Writer: zerolog.LevelWriterAdapter{Writer: w},
Level: loggingConfig.Logging.Console.Level,
})
if loggingConfig.Logging.Console.Level < minOutputLevel {
minOutputLevel = loggingConfig.Logging.Console.Level
}
case "json":
w := output
writers = append(writers, &zerolog.FilteredLevelWriter{
Writer: zerolog.LevelWriterAdapter{Writer: w},
Level: loggingConfig.Logging.Console.Level,
})
if loggingConfig.Logging.Console.Level < minOutputLevel {
minOutputLevel = loggingConfig.Logging.Console.Level
}
case "disable":
// Nothing.
default:
errE := errors.New("invalid console logging type")
errors.Details(errE)["value"] = loggingConfig.Logging.Console.Type
return nil, errE
}
if loggingConfig.Logging.File.Path != "" {
w, err := os.OpenFile(loggingConfig.Logging.File.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, fileMode)
if err != nil {
return nil, errors.WithMessage(err, "cannot open logging file")
}
file = w
writers = append(writers, &zerolog.FilteredLevelWriter{
Writer: zerolog.LevelWriterAdapter{Writer: w},
Level: loggingConfig.Logging.File.Level,
})
if loggingConfig.Logging.File.Level < minOutputLevel {
minOutputLevel = loggingConfig.Logging.File.Level
}
}
zerolog.SetGlobalLevel(zerolog.TraceLevel)
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
// We want only millisecond precision of any timestamp or duration.
zerolog.TimeFieldFormat = TimeFieldFormat
zerolog.DurationFieldUnit = time.Second
// We do not want durations to be more precise than a millisecond, and floating points more than 3 digits as well.
zerolog.FloatingPointPrecision = 3
zerolog.ErrorMarshalFunc = ErrorMarshalFunc //nolint:reassign
// See: https://github.com/rs/zerolog/pull/568
zerolog.InterfaceMarshalFunc = func(v interface{}) ([]byte, error) {
return x.MarshalWithoutEscapeHTML(v)
}
zerolog.ErrorHandler = func(err error) { //nolint:reassign
fmt.Fprintf(os.Stderr, "zerolog: could not write event: % -+#.1v", errors.Formatter{Error: err})
}
writer := zerolog.MultiLevelWriter(writers...)
mainLogger := zerolog.Nop()
mainLoggerLevel := max(minOutputLevel, loggingConfig.Logging.Main.Level)
if len(writers) > 0 && mainLoggerLevel < zerolog.Disabled {
mainLogger = zerolog.New(writer).Level(mainLoggerLevel).With().Timestamp().Logger()
}
log.Logger = mainLogger
loggingConfig.Logger = mainLogger
stdlog.SetFlags(0)
stdlog.SetOutput(mainLogger)
ctxLoggerLevel := max(minOutputLevel, loggingConfig.Logging.Context.Level)
if len(writers) > 0 && ctxLoggerLevel < zerolog.Disabled {
loggingConfig.WithContext = func(ctx context.Context) (context.Context, func(), func()) {
w := &zerolog.TriggerLevelWriter{
Writer: writer,
ConditionalLevel: loggingConfig.Logging.Context.ConditionalLevel,
TriggerLevel: loggingConfig.Logging.Context.TriggerLevel,
}
ctxLogger := zerolog.New(w).Level(ctxLoggerLevel).With().Timestamp().Logger()
closeCtx := func() {
_ = w.Close()
}
trigger := func() {
_ = w.Trigger()
}
return ctxLogger.WithContext(ctx), closeCtx, trigger
}
} else {
loggingConfig.WithContext = func(ctx context.Context) (context.Context, func(), func()) {
ctxLogger := zerolog.Nop()
closeCtx := func() {}
trigger := func() {}
return ctxLogger.WithContext(ctx), closeCtx, trigger
}
}
return file, nil
}
// We initialize kongLevelTypeMapper here so that whole definition does not end
// up in documentation.
var kongLevelTypeMapper = kong.TypeMapper( //nolint:gochecknoglobals
reflect.TypeOf(zerolog.Level(0)),
kong.MapperFunc(func(ctx *kong.DecodeContext, target reflect.Value) error {
var l string
err := ctx.Scan.PopValueInto("level", &l)
if err != nil {
return errors.WithStack(err)
}
level, err := zerolog.ParseLevel(l)
if err != nil {
return errors.WithStack(err)
}
target.Set(reflect.ValueOf(level))
return nil
}),
)
// KongLevelTypeMapper should be used with [Kong]
// initialization so that logging levels found in LoggingConfig struct can be
// correctly parsed on populated.
//
// [Kong]: https://github.com/alecthomas/kong
//
//nolint:gochecknoglobals
var KongLevelTypeMapper = kongLevelTypeMapper
// PrettyLog reads JSON lines from the input and writes to the output
// pretty-printed console lines using ConsoleWriter configured and
// initialized in the same way as New does.
func PrettyLog(noColor bool, input io.Reader, output io.Writer) errors.E {
// First we initialize global zerolog configuration by calling zerolog.New
// with configuration with all logging disabled.
config := LoggingConfig{ //nolint:exhaustruct
Logging: Logging{ //nolint:exhaustruct
Console: Console{ //nolint:exhaustruct
Type: "disable",
},
},
}
_, errE := New(&config)
if errE != nil {
return errE
}
writer := newConsoleWriter(noColor, output)
// Writer expects a whole line at once, so we
// use a scanner to read input line by line.
scanner := bufio.NewScanner(input)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) > 0 {
_, err := writer.Write(line)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
// We have on purpose an empty line between the error and the line.
fmt.Fprintf(os.Stderr, "error: % -+#.1v\n%s\n", errors.Formatter{Error: err}, line)
}
}
}
err := scanner.Err()
if err != nil {
return errors.WithStack(err)
}
return nil
}
// NewHandler injects log into requests context.
//
// Log entries buffered by the context logger are flushed (triggered) if the request panics or
// responds with a server error (status code 500 or higher). For other responses the buffered
// entries are discarded. This makes the detailed debug logging of a request available exactly
// when something went wrong with the request, even when it does not panic and does not itself
// log through the context logger at the triggering level.
func NewHandler(withContext func(context.Context) (context.Context, func(), func())) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx, closeCtx, trigger := withContext(req.Context())
if closeCtx != nil {
defer closeCtx()
}
panicking := true
code := http.StatusOK
if trigger != nil {
defer func() {
if panicking || code >= http.StatusInternalServerError {
trigger()
}
}()
// We capture the response status code so that we can flush buffered log entries on a server
// error even when the request returns normally. If WriteHeader is never called, the response
// status code is 200, which is the default we initialize code with.
w = httpsnoop.Wrap(w, httpsnoop.Hooks{ //nolint:exhaustruct
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(c int) {
code = c
next(c)
}
},
})
}
req = req.WithContext(ctx)
next.ServeHTTP(w, req)
panicking = false
})
}
}