Functions
Add
method
#
Add converts the args to Attrs as described in [Logger.Log],
then appends the Attrs to the [Record]'s list of Attrs.
It omits empty groups.
func (r *Record) Add(args ...any)
AddAttrs
method
#
AddAttrs appends the given Attrs to the [Record]'s list of Attrs.
It omits empty groups.
func (r *Record) AddAttrs(attrs ...Attr)
Any
method
#
Any returns v's value as an any.
func (v Value) Any() any
Any
function
#
Any returns an Attr for the supplied value.
See [AnyValue] for how values are treated.
func Any(key string, value any) Attr
AnyValue
function
#
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
[KindString], [KindBool], [KindUint64], [KindInt64], or [KindFloat64].
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 AnyValue(v any) Value
AppendText
method
#
AppendText implements [encoding.TextAppender]
by calling [Level.AppendText].
func (v *LevelVar) AppendText(b []byte) ([]byte, error)
AppendText
method
#
AppendText implements [encoding.TextAppender]
by calling [Level.String].
func (l Level) AppendText(b []byte) ([]byte, error)
Attrs
method
#
Attrs calls f on each Attr in the [Record].
Iteration stops if f returns false.
func (r Record) Attrs(f func(Attr) bool)
Bool
function
#
Bool returns an Attr for a bool.
func Bool(key string, v bool) Attr
Bool
method
#
Bool returns v's value as a bool. It panics
if v is not a bool.
func (v Value) Bool() bool
BoolValue
function
#
BoolValue returns a [Value] for a bool.
func BoolValue(v bool) Value
Clone
method
#
Clone returns a copy of the record with no shared state.
The original record and the clone can both be modified
without interfering with each other.
func (r Record) Clone() Record
Debug
method
#
Debug logs at [LevelDebug].
func (l *Logger) Debug(msg string, args ...any)
Debug
function
#
Debug calls [Logger.Debug] on the default logger.
func Debug(msg string, args ...any)
DebugContext
function
#
DebugContext calls [Logger.DebugContext] on the default logger.
func DebugContext(ctx context.Context, msg string, args ...any)
DebugContext
method
#
DebugContext logs at [LevelDebug] with the given context.
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
Default
function
#
Default returns the default [Logger].
func Default() *Logger
Duration
method
#
Duration returns v's value as a [time.Duration]. It panics
if v is not a time.Duration.
func (v Value) Duration() time.Duration
Duration
function
#
Duration returns an Attr for a [time.Duration].
func Duration(key string, v time.Duration) Attr
DurationValue
function
#
DurationValue returns a [Value] for a [time.Duration].
func DurationValue(v time.Duration) Value
Enabled
method
#
func (dh discardHandler) Enabled(context.Context, Level) bool
Enabled
method
#
Enabled reports whether l emits log records at the given context and level.
func (l *Logger) Enabled(ctx context.Context, level Level) bool
Enabled
method
#
func (*defaultHandler) Enabled(_ context.Context, l Level) bool
Enabled
method
#
Enabled reports whether the handler handles records at the given level.
The handler ignores records whose level is lower.
func (h *JSONHandler) Enabled(_ context.Context, level Level) bool
Enabled
method
#
Enabled reports whether the handler handles records at the given level.
The handler ignores records whose level is lower.
func (h *TextHandler) Enabled(_ context.Context, level Level) bool
Equal
method
#
Equal reports whether a and b have equal keys and values.
func (a Attr) Equal(b Attr) bool
Equal
method
#
Equal reports whether v and w represent the same Go value.
func (v Value) Equal(w Value) bool
Error
method
#
Error logs at [LevelError].
func (l *Logger) Error(msg string, args ...any)
Error
function
#
Error calls [Logger.Error] on the default logger.
func Error(msg string, args ...any)
ErrorContext
method
#
ErrorContext logs at [LevelError] with the given context.
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
ErrorContext
function
#
ErrorContext calls [Logger.ErrorContext] on the default logger.
func ErrorContext(ctx context.Context, msg string, args ...any)
Float64
function
#
Float64 returns an Attr for a floating-point number.
func Float64(key string, v float64) Attr
Float64
method
#
Float64 returns v's value as a float64. It panics
if v is not a float64.
func (v Value) Float64() float64
Float64Value
function
#
Float64Value returns a [Value] for a floating-point number.
func Float64Value(v float64) Value
Group
function
#
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 Group(key string, args ...any) Attr
Group
method
#
Group returns v's value as a []Attr.
It panics if v's [Kind] is not [KindGroup].
func (v Value) Group() []Attr
GroupValue
function
#
GroupValue returns a new [Value] for a list of Attrs.
The caller must not subsequently mutate the argument slice.
func GroupValue(as ...Attr) Value
Handle
method
#
Handle formats its argument [Record] as a JSON object on a single line.
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.
If the Record's level is zero, the level is omitted.
Otherwise, the 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 as with an [encoding/json.Encoder] with SetEscapeHTML(false),
with two exceptions.
First, an Attr whose Value is of type error is formatted as a string, by
calling its Error method. Only errors in Attrs receive this special treatment,
not errors embedded in structs, slices, maps or other data structures that
are processed by the [encoding/json] package.
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.
func (h *JSONHandler) Handle(_ context.Context, r Record) error
Handle
method
#
Handle formats its argument [Record] as a single line of space-separated
key=value items.
If the Record's time is zero, the time is omitted.
Otherwise, the key is "time"
and the value is output in RFC3339 format with millisecond precision.
If the Record's level is zero, the level is omitted.
Otherwise, the 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 output as FILE:LINE.
The message's key is "msg".
To modify these or other attributes, or remove them from the output, use
[HandlerOptions.ReplaceAttr].
If a value implements [encoding.TextMarshaler], the result of MarshalText is
written. Otherwise, the result of [fmt.Sprint] is written.
Keys and values are quoted with [strconv.Quote] if they contain Unicode space
characters, non-printing characters, '"' or '='.
Keys inside groups consist of components (keys or group names) separated by
dots. No further escaping is performed.
Thus there is no way to determine from the key "a.b.c" whether there
are two groups "a" and "b" and a key "c", or a single group "a.b" and a key "c",
or single group "a" and a key "b.c".
If it is necessary to reconstruct the group structure of a key
even in the presence of dots inside components, use
[HandlerOptions.ReplaceAttr] to encode that information in the key.
Each call to Handle results in a single serialized call to
io.Writer.Write.
func (h *TextHandler) Handle(_ context.Context, r Record) error
Handle
method
#
Collect the level, attributes and message in a string and
write it with the default log.Logger.
Let the log.Logger handle time and file/line.
func (h *defaultHandler) Handle(ctx context.Context, r Record) error
Handle
method
#
func (dh discardHandler) Handle(context.Context, Record) error
Handler
method
#
Handler returns l's Handler.
func (l *Logger) Handler() Handler
Info
function
#
Info calls [Logger.Info] on the default logger.
func Info(msg string, args ...any)
Info
method
#
Info logs at [LevelInfo].
func (l *Logger) Info(msg string, args ...any)
InfoContext
method
#
InfoContext logs at [LevelInfo] with the given context.
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
InfoContext
function
#
InfoContext calls [Logger.InfoContext] on the default logger.
func InfoContext(ctx context.Context, msg string, args ...any)
Int
function
#
Int converts an int to an int64 and returns
an Attr with that value.
func Int(key string, value int) Attr
Int64
function
#
Int64 returns an Attr for an int64.
func Int64(key string, value int64) Attr
Int64
method
#
Int64 returns v's value as an int64. It panics
if v is not a signed integer.
func (v Value) Int64() int64
Int64Value
function
#
Int64Value returns a [Value] for an int64.
func Int64Value(v int64) Value
IntValue
function
#
IntValue returns a [Value] for an int.
func IntValue(v int) Value
Kind
method
#
Kind returns v's Kind.
func (v Value) Kind() Kind
Level
method
#
Level returns the receiver.
It implements [Leveler].
func (l Level) Level() Level
Level
method
#
Level returns v's level.
func (v *LevelVar) Level() Level
Log
method
#
Log emits a log record with the current time and the given level and message.
The Record's Attrs consist of the Logger's attributes followed by
the Attrs specified by args.
The attribute arguments are processed as follows:
- If an argument is an Attr, it is used as is.
- If an argument is a string and this is not the last argument,
the following argument is treated as the value and the two are combined
into an Attr.
- Otherwise, the argument is treated as a value with key "!BADKEY".
func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
Log
function
#
Log calls [Logger.Log] on the default logger.
func Log(ctx context.Context, level Level, msg string, args ...any)
LogAttrs
method
#
LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs.
func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogAttrs
function
#
LogAttrs calls [Logger.LogAttrs] on the default logger.
func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogValuer
method
#
LogValuer returns v's value as a LogValuer. It panics
if v is not a LogValuer.
func (v Value) LogValuer() LogValuer
MarshalJSON
method
#
MarshalJSON implements [encoding/json.Marshaler]
by quoting the output of [Level.String].
func (l Level) MarshalJSON() ([]byte, error)
MarshalText
method
#
MarshalText implements [encoding.TextMarshaler]
by calling [LevelVar.AppendText].
func (v *LevelVar) MarshalText() ([]byte, error)
MarshalText
method
#
MarshalText implements [encoding.TextMarshaler]
by calling [Level.AppendText].
func (l Level) MarshalText() ([]byte, error)
New
function
#
New creates a new Logger with the given non-nil Handler.
func New(h Handler) *Logger
NewJSONHandler
function
#
NewJSONHandler creates a [JSONHandler] that writes to w,
using the given options.
If opts is nil, the default options are used.
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
NewLogLogger
function
#
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 NewLogLogger(h Handler, level Level) *log.Logger
NewRecord
function
#
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.
func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record
NewTextHandler
function
#
NewTextHandler creates a [TextHandler] that writes to w,
using the given options.
If opts is nil, the default options are used.
func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
NumAttrs
method
#
NumAttrs returns the number of attributes in the [Record].
func (r Record) NumAttrs() int
Resolve
method
#
Resolve repeatedly calls LogValue on v while it implements [LogValuer],
and returns the result.
If v resolves to a group, the group's attributes' values are not recursively
resolved.
If the number of LogValue calls exceeds a threshold, a Value containing an
error is returned.
Resolve's return value is guaranteed not to be of Kind [KindLogValuer].
func (v Value) Resolve() (rv Value)
Set
method
#
Set sets v's level to l.
func (v *LevelVar) Set(l Level)
SetDefault
function
#
SetDefault makes l the default [Logger], which is used by
the top-level functions [Info], [Debug] and so on.
After this call, output from the log package's default Logger
(as with [log.Print], etc.) will be logged using l's Handler,
at a level controlled by [SetLogLoggerLevel].
func SetDefault(l *Logger)
SetLogLoggerLevel
function
#
SetLogLoggerLevel controls the level for the bridge to the [log] package.
Before [SetDefault] is called, slog top-level logging functions call the default [log.Logger].
In that mode, SetLogLoggerLevel sets the minimum level for those calls.
By default, the minimum level is Info, so calls to [Debug]
(as well as top-level logging calls at lower levels)
will not be passed to the log.Logger. After calling
slog.SetLogLoggerLevel(slog.LevelDebug)
calls to [Debug] will be passed to the log.Logger.
After [SetDefault] is called, calls to the default [log.Logger] are passed to the
slog default handler. In that mode,
SetLogLoggerLevel sets the level at which those calls are logged.
That is, after calling
slog.SetLogLoggerLevel(slog.LevelDebug)
A call to [log.Printf] will result in output at level [LevelDebug].
SetLogLoggerLevel returns the previous value.
func SetLogLoggerLevel(level Level) (oldLevel Level)
String
method
#
String returns a name for the level.
If the level has a name, then that name
in uppercase is returned.
If the level is between named values, then
an integer is appended to the uppercased name.
Examples:
LevelWarn.String() => "WARN"
(LevelInfo+2).String() => "INFO+2"
func (l Level) String() string
String
method
#
func (k Kind) String() string
String
method
#
func (a Attr) String() string
String
function
#
String returns an Attr for a string value.
func String(key string, value string) Attr
String
method
#
func (v *LevelVar) String() string
String
method
#
String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike
the methods Int64, Float64, and so on, which panic if v is of the
wrong kind, String never panics.
func (v Value) String() string
StringValue
function
#
StringValue returns a new [Value] for a string.
func StringValue(value string) Value
Time
method
#
Time returns v's value as a [time.Time]. It panics
if v is not a time.Time.
func (v Value) Time() time.Time
Time
function
#
Time returns an Attr for a [time.Time].
It discards the monotonic portion.
func Time(key string, v time.Time) Attr
TimeValue
function
#
TimeValue returns a [Value] for a [time.Time].
It discards the monotonic portion.
func TimeValue(v time.Time) Value
Uint64
function
#
Uint64 returns an Attr for a uint64.
func Uint64(key string, v uint64) Attr
Uint64
method
#
Uint64 returns v's value as a uint64. It panics
if v is not an unsigned integer.
func (v Value) Uint64() uint64
Uint64Value
function
#
Uint64Value returns a [Value] for a uint64.
func Uint64Value(v uint64) Value
UnmarshalJSON
method
#
UnmarshalJSON implements [encoding/json.Unmarshaler]
It accepts any string produced by [Level.MarshalJSON],
ignoring case.
It also accepts numeric offsets that would result in a different string on
output. For example, "Error-8" would marshal as "INFO".
func (l *Level) UnmarshalJSON(data []byte) error
UnmarshalText
method
#
UnmarshalText implements [encoding.TextUnmarshaler].
It accepts any string produced by [Level.MarshalText],
ignoring case.
It also accepts numeric offsets that would result in a different string on
output. For example, "Error-8" would marshal as "INFO".
func (l *Level) UnmarshalText(data []byte) error
UnmarshalText
method
#
UnmarshalText implements [encoding.TextUnmarshaler]
by calling [Level.UnmarshalText].
func (v *LevelVar) UnmarshalText(data []byte) error
Warn
method
#
Warn logs at [LevelWarn].
func (l *Logger) Warn(msg string, args ...any)
Warn
function
#
Warn calls [Logger.Warn] on the default logger.
func Warn(msg string, args ...any)
WarnContext
function
#
WarnContext calls [Logger.WarnContext] on the default logger.
func WarnContext(ctx context.Context, msg string, args ...any)
WarnContext
method
#
WarnContext logs at [LevelWarn] with the given context.
func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
With
method
#
With returns a Logger that includes the given attributes
in each output operation. Arguments are converted to
attributes as if by [Logger.Log].
func (l *Logger) With(args ...any) *Logger
With
function
#
With calls [Logger.With] on the default logger.
func With(args ...any) *Logger
WithAttrs
method
#
WithAttrs returns a new [TextHandler] whose attributes consists
of h's attributes followed by attrs.
func (h *TextHandler) WithAttrs(attrs []Attr) Handler
WithAttrs
method
#
func (h *defaultHandler) WithAttrs(as []Attr) Handler
WithAttrs
method
#
func (dh discardHandler) WithAttrs(attrs []Attr) Handler
WithAttrs
method
#
WithAttrs returns a new [JSONHandler] whose attributes consists
of h's attributes followed by attrs.
func (h *JSONHandler) WithAttrs(attrs []Attr) Handler
WithGroup
method
#
func (h *TextHandler) WithGroup(name string) Handler
WithGroup
method
#
WithGroup returns a Logger that starts a group, if name is non-empty.
The keys of all attributes added to the Logger will be qualified by the given
name. (How that qualification happens depends on the [Handler.WithGroup]
method of the Logger's Handler.)
If name is empty, WithGroup returns the receiver.
func (l *Logger) WithGroup(name string) *Logger
WithGroup
method
#
func (dh discardHandler) WithGroup(name string) Handler
WithGroup
method
#
func (h *defaultHandler) WithGroup(name string) Handler
WithGroup
method
#
func (h *JSONHandler) WithGroup(name string) Handler
Write
method
#
func (w *handlerWriter) Write(buf []byte) (int, error)
append
method
#
append appends a text representation of v to dst.
v is formatted as with fmt.Sprint.
func (v Value) append(dst []byte) []byte
appendAttr
method
#
appendAttr appends the Attr's key and value.
It handles replacement and checking for an empty key.
It reports whether something was appended.
func (s *handleState) appendAttr(a Attr) bool
appendAttrs
method
#
appendAttrs appends the slice of Attrs.
It reports whether something was appended.
func (s *handleState) appendAttrs(as []Attr) bool
appendError
method
#
func (s *handleState) appendError(err error)
appendEscapedJSONString
function
#
appendEscapedJSONString escapes s for JSON and appends it to buf.
It does not surround the string in quotation marks.
Modified from encoding/json/encode.go:encodeState.string,
with escapeHTML set to false.
func appendEscapedJSONString(buf []byte, s string) []byte
appendJSONMarshal
function
#
func appendJSONMarshal(buf *buffer.Buffer, v any) error
appendJSONTime
function
#
Adapted from time.Time.MarshalJSON to avoid allocation.
func appendJSONTime(s *handleState, t time.Time)
appendJSONValue
function
#
func appendJSONValue(s *handleState, v Value) error
appendKey
method
#
func (s *handleState) appendKey(key string)
appendNonBuiltIns
method
#
func (s *handleState) appendNonBuiltIns(r Record)
appendRFC3339Millis
function
#
func appendRFC3339Millis(b []byte, t time.Time) []byte
appendString
method
#
func (s *handleState) appendString(str string)
appendTextValue
function
#
func appendTextValue(s *handleState, v Value) error
appendTime
method
#
func (s *handleState) appendTime(t time.Time)
appendValue
method
#
func (s *handleState) appendValue(v Value)
argsToAttr
function
#
argsToAttr turns a prefix of the nonempty args slice into an Attr
and returns the unconsumed portion of the slice.
If args[0] is an Attr, it returns it.
If args[0] is a string, it treats the first two elements as
a key-value pair.
Otherwise, it treats args[0] as a value with a missing key.
func argsToAttr(args []any) (Attr, []any)
argsToAttrSlice
function
#
func argsToAttrSlice(args []any) []Attr
attrSep
method
#
attrSep returns the separator between attributes.
func (h *commonHandler) attrSep() string
bool
method
#
func (v Value) bool() bool
byteSlice
function
#
byteSlice returns its argument as a []byte if the argument's
underlying type is []byte, along with a second return value of true.
Otherwise it returns nil, false.
func byteSlice(a any) ([]byte, bool)
clone
method
#
func (h *commonHandler) clone() *commonHandler
clone
method
#
func (l *Logger) clone() *Logger
closeGroup
method
#
closeGroup ends the group with the given name.
func (s *handleState) closeGroup(name string)
countAttrs
function
#
countAttrs returns the number of Attrs that would be created from args.
func countAttrs(args []any) int
countEmptyGroups
function
#
countEmptyGroups returns the number of empty group values in its argument.
func countEmptyGroups(as []Attr) int
duration
method
#
func (v Value) duration() time.Duration
enabled
method
#
enabled reports whether l is greater than or equal to the
minimum level.
func (h *commonHandler) enabled(l Level) bool
float
method
#
func (v Value) float() float64
free
method
#
func (s *handleState) free()
group
method
#
group returns the non-zero fields of s as a slice of attrs.
It is similar to a LogValue method, but we don't want Source
to implement LogValuer because it would be resolved before
the ReplaceAttr function was called.
func (s *Source) group() Value
group
method
#
func (v Value) group() []Attr
handle
method
#
handle is the internal implementation of Handler.Handle
used by TextHandler and JSONHandler.
func (h *commonHandler) handle(r Record) error
init
function
#
func init()
isEmpty
method
#
isEmpty reports whether a has an empty key and a nil value.
That can be written as Attr{} or Any("", nil).
func (a Attr) isEmpty() bool
isEmptyGroup
method
#
isEmptyGroup reports whether v is a group that has no attributes.
func (v Value) isEmptyGroup() bool
log
method
#
log is the low-level logging method for methods that take ...any.
It must always be called directly by an exported logging method
or function, because it uses a fixed call depth to obtain the pc.
func (l *Logger) log(ctx context.Context, level Level, msg string, args ...any)
logAttrs
method
#
logAttrs is like [Logger.log], but for methods that take ...Attr.
func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
needsQuoting
function
#
func needsQuoting(s string) bool
newDefaultHandler
function
#
func newDefaultHandler(output func(uintptr, []byte) error) *defaultHandler
newHandleState
method
#
func (h *commonHandler) newHandleState(buf *buffer.Buffer, freeBuf bool, sep string) handleState
openGroup
method
#
openGroup starts a new group of attributes
with the given name.
func (s *handleState) openGroup(name string)
openGroups
method
#
func (s *handleState) openGroups()
parse
method
#
func (l *Level) parse(s string) (err error)
source
method
#
source returns a Source for the log event.
If the Record was created without the necessary information,
or if the location is unavailable, it returns a non-nil *Source
with zero fields.
func (r Record) source() *Source
stack
function
#
func stack(skip int, nFrames int) string
str
method
#
func (v Value) str() string
time
method
#
See TimeValue to understand how times are represented.
func (v Value) time() time.Time
withAttrs
method
#
func (h *commonHandler) withAttrs(as []Attr) *commonHandler
withGroup
method
#
func (h *commonHandler) withGroup(name string) *commonHandler