|
1 |
| -// Package slogjson contains the slogger |
2 |
| -// that writes logs in a JSON format. |
| 1 | +// Package slogjson contains the slogger that writes logs in a JSON format. |
| 2 | +// |
| 3 | +// Format |
| 4 | +// |
| 5 | +// { |
| 6 | +// "level": "INFO", |
| 7 | +// "msg": "hi", |
| 8 | +// "ts": "", |
| 9 | +// "caller": "slog/examples_test.go:62", |
| 10 | +// "func": "go.coder.com/slog/sloggers/slogtest_test.TestExampleTest", |
| 11 | +// "component": "comp.subcomp", |
| 12 | +// "trace": "<traceid>", |
| 13 | +// "span": "<spanid>", |
| 14 | +// "fields": { |
| 15 | +// "myField": "fieldValue" |
| 16 | +// } |
| 17 | +// } |
3 | 18 | package slogjson // import "go.coder.com/slog/sloggers/slogjson"
|
4 | 19 |
|
5 | 20 | import (
|
| 21 | + "context" |
| 22 | + "encoding/json" |
| 23 | + "fmt" |
6 | 24 | "io"
|
| 25 | + "time" |
| 26 | + |
| 27 | + "go.opencensus.io/trace" |
| 28 | + "golang.org/x/xerrors" |
7 | 29 |
|
8 | 30 | "go.coder.com/slog"
|
| 31 | + "go.coder.com/slog/internal/syncwriter" |
| 32 | + "go.coder.com/slog/slogval" |
9 | 33 | )
|
10 | 34 |
|
11 | 35 | // Make creates a logger that writes JSON logs
|
12 |
| -// to the given writer. The format is as follows: |
| 36 | +// to the given writer. See package level docs |
| 37 | +// for the format. |
13 | 38 | func Make(w io.Writer) slog.Logger {
|
14 |
| - panic("TODO") |
| 39 | + return slog.Make(jsonSink{ |
| 40 | + w: syncwriter.New(w), |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +type jsonSink struct { |
| 45 | + w *syncwriter.Writer |
| 46 | +} |
| 47 | + |
| 48 | +func (s jsonSink) LogEntry(ctx context.Context, ent slog.Entry) { |
| 49 | + m := slog.Map( |
| 50 | + slog.F("level", ent.Level), |
| 51 | + slog.F("msg", ent.Message), |
| 52 | + slog.F("ts", jsonTimestamp(ent.Time)), |
| 53 | + slog.F("caller", fmt.Sprintf("%v:%v", ent.File, ent.Line)), |
| 54 | + slog.F("func", ent.Func), |
| 55 | + slog.F("component", ent.Component), |
| 56 | + ) |
| 57 | + |
| 58 | + if ent.SpanContext != (trace.SpanContext{}) { |
| 59 | + m = append(m, |
| 60 | + slog.F("trace", ent.SpanContext.TraceID), |
| 61 | + slog.F("span", ent.SpanContext.SpanID), |
| 62 | + ) |
| 63 | + } |
| 64 | + |
| 65 | + m = append(m, |
| 66 | + slog.F("fields", ent.Fields), |
| 67 | + ) |
| 68 | + |
| 69 | + v := slogval.Reflect(m) |
| 70 | + // We use NewEncoder because it reuses buffers behind the scenes which we cannot |
| 71 | + // do with json.Marshal. |
| 72 | + e := json.NewEncoder(s.w) |
| 73 | + e.Encode(v) |
| 74 | +} |
| 75 | + |
| 76 | +func jsonTimestamp(t time.Time) interface{} { |
| 77 | + ts, err := t.MarshalText() |
| 78 | + if err != nil { |
| 79 | + return xerrors.Errorf("failed to marshal timestamp to text: %w", err) |
| 80 | + } |
| 81 | + return string(ts) |
15 | 82 | }
|
0 commit comments