slog

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2023 License: BSD-3-Clause Imports: 5 Imported by: 19

README

slog shim

GitHub Workflow Status go.dev reference Go Version built with nix

Go 1.21 introduced a new structured logging package, log/slog, to the standard library. Although it's been eagerly anticipated by many, widespread adoption isn't expected to occur immediately, especially since updating to Go 1.21 is a decision that most libraries won't make overnight.

Before this package was added to the standard library, there was an experimental version available at golang.org/x/exp/slog. While it's generally advised against using experimental packages in production, this one served as a sort of backport package for the last few years, incorporating new features before they were added to the standard library (like slices, maps or errors).

This package serves as a bridge, helping libraries integrate slog in a backward-compatible way without having to immediately update their Go version requirement to 1.21. On Go 1.21 (and above), it acts as a drop-in replacement for log/slog, while below 1.21 it falls back to golang.org/x/exp/slog.

How does it achieve backwards compatibility?

Although there's no consensus on whether dropping support for older Go versions is considered backward compatible, a majority seems to believe it is. (I don't have scientific proof for this, but it's based on conversations with various individuals across different channels.)

This package adheres to that interpretation of backward compatibility. On Go 1.21, the shim uses type aliases to offer the same API as slog/log. Once a library upgrades its version requirement to Go 1.21, it should be able to discard this shim and use log/slog directly.

For older Go versions, the library might become unstable after removing the shim. However, since those older versions are no longer supported, the promise of backward compatibility remains intact.

Installation

go get github.com/sagikazarmark/slog-shim

Usage

Import this package into your library and use it in your public API:

package mylib

import slog "github.com/sagikazarmark/slog-shim"

func New(logger *slog.Logger) MyLib {
    // ...
}

When using the library, clients can either use log/slog (when on Go 1.21) or golang.org/x/exp/slog (below Go 1.21):

package main

import "log/slog"

// OR

import "golang.org/x/exp/slog"

mylib.New(slog.Default())

Make sure consumers are aware that your API behaves differently on different Go versions.

Once you bump your Go version requirement to Go 1.21, you can drop the shim entirely from your code:

package mylib

- import slog "github.com/sagikazarmark/slog-shim"
+ import "log/slog"

func New(logger *slog.Logger) MyLib {
    // ...
}

License

The project is licensed under a BSD-style license.

Documentation

Index

Constants

View Source
const (
	// TimeKey is the key used by the built-in handlers for the time
	// when the log method is called. The associated Value is a [time.Time].
	TimeKey = slog.TimeKey
	// LevelKey is the key used by the built-in handlers for the level
	// of the log call. The associated value is a [Level].
	LevelKey = slog.LevelKey
	// MessageKey is the key used by the built-in handlers for the
	// message of the log call. The associated value is a string.
	MessageKey = slog.MessageKey
	// SourceKey is the key used by the built-in handlers for the source file
	// and line of the log call. The associated value is a string.
	SourceKey = slog.SourceKey
)

Keys for "built-in" attributes.

View Source
const (
	KindAny       = slog.KindAny
	KindBool      = slog.KindBool
	KindDuration  = slog.KindDuration
	KindFloat64   = slog.KindFloat64
	KindInt64     = slog.KindInt64
	KindString    = slog.KindString
	KindTime      = slog.KindTime
	KindUint64    = slog.KindUint64
	KindGroup     = slog.KindGroup
	KindLogValuer = slog.KindLogValuer
)

The following list is sorted alphabetically, but it's also important that KindAny is 0 so that a zero Value represents nil.

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, args ...any)

Debug calls Logger.Debug on the default logger.

func DebugContext

func DebugContext(ctx context.Context, msg string, args ...any)

DebugContext calls Logger.DebugContext on the default logger.

func Error

func Error(msg string, args ...any)

Error calls Logger.Error on the default logger.

func ErrorContext

func ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext calls Logger.ErrorContext on the default logger.

func Info

func Info(msg string, args ...any)

Info calls Logger.Info on the default logger.

func InfoContext

func InfoContext(ctx context.Context, msg string, args ...any)

InfoContext calls Logger.InfoContext on the default logger.

func Log

func Log(ctx context.Context, level Level, msg string, args ...any)

Log calls Logger.Log on the default logger.

func LogAttrs

func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

LogAttrs calls Logger.LogAttrs on the default logger.

func NewLogLogger

func NewLogLogger(h Handler, level Level) *log.Logger

NewLogLogger returns a new log.Logger such that each call to its Output method dispatches a Record to the specified handler. The logger acts as a bridge from the older log API to newer structured logging handlers.

func SetDefault

func SetDefault(l *Logger)

SetDefault makes l the default Logger. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged at LevelInfo using l's Handler.

func Warn

func Warn(msg string, args ...any)

Warn calls Logger.Warn on the default logger.

func WarnContext

func WarnContext(ctx context.Context, msg string, args ...any)

WarnContext calls Logger.WarnContext on the default logger.

Types

type Attr

type Attr = slog.Attr

An Attr is a key-value pair.

func Any

func Any(key string, value any) Attr

Any returns an Attr for the supplied value. See [Value.AnyValue] for how values are treated.

func Bool

func Bool(key string, v bool) Attr

Bool returns an Attr for a bool.

func Duration

func Duration(key string, v time.Duration) Attr

Duration returns an Attr for a time.Duration.

func Float64

func Float64(key string, v float64) Attr

Float64 returns an Attr for a floating-point number.

func Group

func Group(key string, args ...any) Attr

Group returns an Attr for a Group Value. The first argument is the key; the remaining arguments are converted to Attrs as in [Logger.Log].

Use Group to collect several key-value pairs under a single key on a log line, or as the result of LogValue in order to log a single value as multiple Attrs.

func Int

func Int(key string, value int) Attr

Int converts an int to an int64 and returns an Attr with that value.

func Int64

func Int64(key string, value int64) Attr

Int64 returns an Attr for an int64.

func String

func String(key, value string) Attr

String returns an Attr for a string value.

func Time

func Time(key string, v time.Time) Attr

Time returns an Attr for a time.Time. It discards the monotonic portion.

func Uint64

func Uint64(key string, v uint64) Attr

Uint64 returns an Attr for a uint64.

type Handler

type Handler = slog.Handler

A Handler handles log records produced by a Logger..

A typical handler may print log records to standard error, or write them to a file or database, or perhaps augment them with additional attributes and pass them on to another handler.

Any of the Handler's methods may be called concurrently with itself or with other methods. It is the responsibility of the Handler to manage this concurrency.

Users of the slog package should not invoke Handler methods directly. They should use the methods of Logger instead.

type HandlerOptions

type HandlerOptions = slog.HandlerOptions

HandlerOptions are options for a TextHandler or JSONHandler. A zero HandlerOptions consists entirely of default values.

type JSONHandler

type JSONHandler = slog.JSONHandler

JSONHandler is a Handler that writes Records to an io.Writer as line-delimited JSON objects.

func NewJSONHandler

func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler

NewJSONHandler creates a JSONHandler that writes to w, using the given options. If opts is nil, the default options are used.

type Kind

type Kind = slog.Kind

Kind is the kind of a Value.

type Level

type Level = slog.Level

A Level is the importance or severity of a log event. The higher the level, the more important or severe the event.

const (
	LevelDebug Level = slog.LevelDebug
	LevelInfo  Level = slog.LevelInfo
	LevelWarn  Level = slog.LevelWarn
	LevelError Level = slog.LevelError
)

Level numbers are inherently arbitrary, but we picked them to satisfy three constraints. Any system can map them to another numbering scheme if it wishes.

First, we wanted the default level to be Info, Since Levels are ints, Info is the default value for int, zero.

Second, we wanted to make it easy to use levels to specify logger verbosity. Since a larger level means a more severe event, a logger that accepts events with smaller (or more negative) level means a more verbose logger. Logger verbosity is thus the negation of event severity, and the default verbosity of 0 accepts all events at least as severe as INFO.

Third, we wanted some room between levels to accommodate schemes with named levels between ours. For example, Google Cloud Logging defines a Notice level between Info and Warn. Since there are only a few of these intermediate levels, the gap between the numbers need not be large. Our gap of 4 matches OpenTelemetry's mapping. Subtracting 9 from an OpenTelemetry level in the DEBUG, INFO, WARN and ERROR ranges converts it to the corresponding slog Level range. OpenTelemetry also has the names TRACE and FATAL, which slog does not. But those OpenTelemetry levels can still be represented as slog Levels by using the appropriate integers.

Names for common levels.

type LevelVar

type LevelVar = slog.LevelVar

A LevelVar is a Level variable, to allow a Handler level to change dynamically. It implements Leveler as well as a Set method, and it is safe for use by multiple goroutines. The zero LevelVar corresponds to LevelInfo.

type Leveler

type Leveler = slog.Leveler

A Leveler provides a Level value.

As Level itself implements Leveler, clients typically supply a Level value wherever a Leveler is needed, such as in HandlerOptions. Clients who need to vary the level dynamically can provide a more complex Leveler implementation such as *LevelVar.

type LogValuer

type LogValuer = slog.LogValuer

A LogValuer is any Go value that can convert itself into a Value for logging.

This mechanism may be used to defer expensive operations until they are needed, or to expand a single value into a sequence of components.

type Logger

type Logger = slog.Logger

A Logger records structured information about each call to its Log, Debug, Info, Warn, and Error methods. For each call, it creates a Record and passes it to a Handler.

To create a new Logger, call New or a Logger method that begins "With".

func Default

func Default() *Logger

Default returns the default Logger.

func New

func New(h Handler) *Logger

New creates a new Logger with the given non-nil Handler.

func With

func With(args ...any) *Logger

With calls Logger.With on the default logger.

type Record

type Record = slog.Record

A Record holds information about a log event. Copies of a Record share state. Do not modify a Record after handing out a copy to it. Call NewRecord to create a new Record. Use [Record.Clone] to create a copy with no shared state.

func NewRecord

func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record

NewRecord creates a Record from the given arguments. Use [Record.AddAttrs] to add attributes to the Record.

NewRecord is intended for logging APIs that want to support a Handler as a backend.

type Source

type Source = slog.Source

Source describes the location of a line of source code.

type TextHandler

type TextHandler = slog.TextHandler

TextHandler is a Handler that writes Records to an io.Writer as a sequence of key=value pairs separated by spaces and followed by a newline.

func NewTextHandler

func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler

NewTextHandler creates a TextHandler that writes to w, using the given options. If opts is nil, the default options are used.

type Value

type Value = slog.Value

A Value can represent any Go value, but unlike type any, it can represent most small values without an allocation. The zero Value corresponds to nil.

func AnyValue

func AnyValue(v any) Value

AnyValue returns a Value for the supplied value.

If the supplied value is of type Value, it is returned unmodified.

Given a value of one of Go's predeclared string, bool, or (non-complex) numeric types, AnyValue returns a Value of kind String, Bool, Uint64, Int64, or Float64. The width of the original numeric type is not preserved.

Given a time.Time or time.Duration value, AnyValue returns a Value of kind KindTime or KindDuration. The monotonic time is not preserved.

For nil, or values of all other types, including named types whose underlying type is numeric, AnyValue returns a value of kind KindAny.

func BoolValue

func BoolValue(v bool) Value

BoolValue returns a Value for a bool.

func DurationValue

func DurationValue(v time.Duration) Value

DurationValue returns a Value for a time.Duration.

func Float64Value

func Float64Value(v float64) Value

Float64Value returns a Value for a floating-point number.

func GroupValue

func GroupValue(as ...Attr) Value

GroupValue returns a new Value for a list of Attrs. The caller must not subsequently mutate the argument slice.

func Int64Value

func Int64Value(v int64) Value

Int64Value returns a Value for an int64.

func IntValue

func IntValue(v int) Value

IntValue returns a Value for an int.

func StringValue

func StringValue(value string) Value

StringValue returns a new Value for a string.

func TimeValue

func TimeValue(v time.Time) Value

TimeValue returns a Value for a time.Time. It discards the monotonic portion.

func Uint64Value

func Uint64Value(v uint64) Value

Uint64Value returns a Value for a uint64.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL