...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package slogjson
19
20 import (
21 "context"
22 "encoding/json"
23 "fmt"
24 "io"
25
26 "go.opencensus.io/trace"
27
28 "cdr.dev/slog"
29 "cdr.dev/slog/internal/syncwriter"
30 )
31
32
33
34
35
36
37 func Sink(w io.Writer) slog.Sink {
38 return jsonSink{
39 w: syncwriter.New(w),
40 }
41 }
42
43 type jsonSink struct {
44 w *syncwriter.Writer
45 }
46
47 func (s jsonSink) LogEntry(ctx context.Context, ent slog.SinkEntry) {
48 m := slog.M(
49 slog.F("ts", ent.Time),
50 slog.F("level", ent.Level),
51 slog.F("msg", ent.Message),
52 slog.F("caller", fmt.Sprintf("%v:%v", ent.File, ent.Line)),
53 slog.F("func", ent.Func),
54 )
55
56 if len(ent.LoggerNames) > 0 {
57 m = append(m, slog.F("logger_names", ent.LoggerNames))
58 }
59
60 if ent.SpanContext != (trace.SpanContext{}) {
61 m = append(m,
62 slog.F("trace", ent.SpanContext.TraceID),
63 slog.F("span", ent.SpanContext.SpanID),
64 )
65 }
66
67 if len(ent.Fields) > 0 {
68 m = append(m,
69 slog.F("fields", ent.Fields),
70 )
71 }
72
73 buf, _ := json.Marshal(m)
74
75 buf = append(buf, '\n')
76 s.w.Write("slogjson", buf)
77 }
78
79 func (s jsonSink) Sync() {
80 s.w.Sync("slogjson")
81 }
82
View as plain text