Documentation
¶
Overview ¶
Package slogjson lets you format your Golang structured logging log/slog usingthe JSON v2 library github.com/go-json-experiment/json, with optional single-line pretty-printing.
This is so much easier to read than the default json:
{"time":"2000-01-02T03:04:05Z", "level":"INFO", "msg":"m", "attr":{"nest":1234}}
or
{"time": "2000-01-02T03:04:05Z", "level": "INFO", "msg": "m", "attr": {"nest": 1234}}
Versus the default standard library JSON Handler:
{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"m","attr":{"nest":"1234"}}
Additional benefits:
- JSON v2 is faster than the stdlib JSON v1 (up to 9x faster).
- Can make use of all marshaling and encoding options JSON v2 has available.
- Improved correctness and behavior with JSON v2. See: https://github.com/golang/go/discussions/63397
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReplaceAttrTruncate ¶ added in v0.5.0
func ReplaceAttrTruncate(maxLogFieldLength int, jsonOptions jsonv2.Options) func(group []string, a slog.Attr) slog.Attr
ReplaceAttrTruncate is a replacement function that examines attributes before they are logged and if necessary truncates them. AWS Cloudwatch has a limit of 256kb, GCP Stackdriver is 100kb, Azure is 32kb total and 8kb per field, docker is 16kb, some Java based systems have a max of 8221. Since there can be multiple fields, and it is a lot harder to control total length, set the field length a bit shorter.
Types ¶
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is a log/slog.Handler that writes Records to an io.Writer as line-delimited JSON objects.
func NewHandler ¶
func NewHandler(w io.Writer, opts *HandlerOptions) *Handler
NewHandler creates a Handler that writes to w, using the given options. If opts is nil, the default options are used.
func (*Handler) Enabled ¶
Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.
func (*Handler) Handle ¶
Handle formats its argument [Record] as a JSON object.
If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output as with json.Marshal.
The level's key is "level" and the value of [Level.String] is output.
If the AddSource option is set and source information is available, the key is "source", and the value is a record of type [Source].
The message's key is "msg".
To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].
Values are formatted using the provided json.Options, with two exceptions.
First, an Attr whose Value is of type error is formatted as a string, by calling its Error method, if the error type does not implement json.Marshaler or json.MarshalerTo, and the json options provided does not include any json.Marshalers for this type. This affects nested errors and errors present in slices as well.
Second, an encoding failure does not cause Handle to return an error. Instead, the error message is formatted as a string.
Each call to Handle results in a single serialized call to io.Writer.Write.
type HandlerOptions ¶
type HandlerOptions struct {
// AddSource causes the handler to compute the source code position
// of the log statement and add a SourceKey attribute to the output.
AddSource bool
// Level reports the minimum record level that will be logged.
// The handler discards records with lower levels.
// If Level is nil, the handler assumes LevelInfo.
// The handler calls Level.Level for each record processed;
// to adjust the minimum level dynamically, use a LevelVar.
Level slog.Leveler
// ReplaceAttr is called to rewrite each non-group attribute before it is logged.
// The attribute's value has been resolved (see [Value.Resolve]).
// If ReplaceAttr returns a zero Attr, the attribute is discarded.
//
// The built-in attributes with keys "time", "level", "source", and "msg"
// are passed to this function, except that time is omitted
// if zero, and source is omitted if AddSource is false.
//
// The first argument is a list of currently open groups that contain the
// Attr. It must not be retained or modified. ReplaceAttr is never called
// for Group attributes, only their contents. For example, the attribute
// list
//
// Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
//
// results in consecutive calls to ReplaceAttr with the following arguments:
//
// nil, Int("a", 1)
// []string{"g"}, Int("b", 2)
// nil, Int("c", 3)
//
// ReplaceAttr can be used to change the default keys of the built-in
// attributes, convert types (for example, to replace a `time.Time` with the
// integer seconds since the Unix epoch), sanitize personal information, or
// remove attributes from the output.
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
// JSONOptions is a set of options created with [json.JoinOptions] for
// configuring the json v2 library.
// If not configured, the defaults will be:
// json.Deterministic(true),
// json.DiscardUnknownMembers(false),
// json.FormatNilMapAsNull(false),
// json.FormatNilSliceAsNull(false),
// json.MatchCaseInsensitiveNames(false),
// json.OmitZeroStructFields(false),
// json.StringifyNumbers(false),
// json.RejectUnknownMembers(false),
// jsontext.AllowDuplicateNames(true),
// jsontext.AllowInvalidUTF8(true),
// jsontext.EscapeForHTML(false),
// jsontext.EscapeForJS(true),
// jsontext.Multiline(false),
// jsontext.PreserveRawStrings(false),
// jsontext.ReorderRawObjects(false),
// jsontext.SpaceAfterColon(false),
// jsontext.SpaceAfterComma(true),
// (no ident)
JSONOptions jsontext.Options
}
HandlerOptions are options for a Handler. A zero HandlerOptions consists entirely of default values.