...

Source file src/cdr.dev/slog/sloggers/slogjson/slogjson.go

Documentation: cdr.dev/slog/sloggers/slogjson

     1  // Package slogjson contains the slogger that writes logs in JSON.
     2  //
     3  // Format
     4  //
     5  //	{
     6  //	  "ts": "2019-09-10T20:19:07.159852-05:00",
     7  //	  "level": "INFO",
     8  //	  "logger_names": ["comp", "subcomp"],
     9  //	  "msg": "hi",
    10  //	  "caller": "slog/examples_test.go:62",
    11  //	  "func": "cdr.dev/slog/sloggers/slogtest_test.TestExampleTest",
    12  //	  "trace": "<traceid>",
    13  //	  "span": "<spanid>",
    14  //	  "fields": {
    15  //	    "my_field": "field value"
    16  //	  }
    17  //	}
    18  package slogjson // import "cdr.dev/slog/sloggers/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  // Sink creates a slog.Sink that writes JSON logs
    33  // to the given writer. See package level docs
    34  // for the format.
    35  // If the writer implements Sync() error then
    36  // it will be called when syncing.
    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