slog

package
v1.2.94 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2023 License: MIT Imports: 25 Imported by: 5

Documentation

Overview

Example (Wrapping)
package main

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

// Infof is an example of a user-defined logging function that wraps slog.
// The log record contains the source position of the caller of Infof.
func Infof(logger *slog.Logger, format string, args ...any) {
	if !logger.Enabled(context.Background(), slog.LevelInfo) {
		return
	}
	var pcs [1]uintptr
	runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
	r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
	_ = logger.Handler().Handle(context.Background(), r)
}

func main() {
	getPid = func() int { return 0 } // set pid to zero for test
	defer func() { getPid = os.Getpid }()
	replace := func(groups []string, a slog.Attr) slog.Attr {
		// Remove time.
		if a.Key == slog.TimeKey && len(groups) == 0 {
			return slog.Attr{}
		}
		// Remove the directory from the source's filename.
		if a.Key == slog.SourceKey {
			source := a.Value.Any().(*slog.Source)
			source.File = filepath.Base(source.File)
		}
		return a
	}
	{
		fmt.Printf("----text----\n")
		logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
		Infof(logger, "message, %s", "formatted")
	}
	{
		fmt.Printf("----glog----\n")
		logger := slog.New(NewGlogHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
		Infof(logger, "message, %s", "formatted")
	}
	{
		fmt.Printf("----glog_human----\n")
		logger := slog.New(NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
		Infof(logger, "message, %s", "formatted")
	}

}
Output:

----text----
level=INFO source=example_wrap_test.go:47 msg="message, formatted"
----glog----
I 0 example_wrap_test.go:52] message, formatted
----glog_human----
[INFO ] [0] [example_wrap_test.go:57](Example_wrapping) message, formatted

Index

Examples

Constants

View Source
const (
	// ErrorKey is the key used by the handlers for the error
	// when the log method is called. The associated Value is an [error].
	ErrorKey = "error"
)

Keys for "built-in" attributes.

Variables

View Source
var ShortCallerPrettyfier = func(f *runtime.Frame) (function string, file string) {
	funcname := path.Base(f.Function)
	filename := path.Base(f.File)
	return fmt.Sprintf("%s()", funcname), fmt.Sprintf("%s:%d", filename, f.Line)
}

ShortCallerPrettyfier modify the content of the function and file keys in the data when ReportCaller is activated. INFO[0000] main.go:23 main() hello world

Functions

func Error added in v1.2.89

func Error(err error) slog.Attr

Error returns an Attr for an error value.

func GlogRotateHeader added in v1.2.86

func GlogRotateHeader(name string)

GlogRotateHeader append rotate header to a file named by filename.

func MultiHandler

func MultiHandler(handlers ...slog.Handler) slog.Handler

MultiHandler creates a slog.Handler that duplicates its writes to all the provided handlers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

func MultiReplaceAttr

func MultiReplaceAttr(replacers ...func(groups []string, a slog.Attr) slog.Attr) func(groups []string, a slog.Attr) slog.Attr

MultiReplaceAttr creates a [ReplaceAttr] that call all the provided replacers one by one

func NewCommonHandler

func NewCommonHandler(w io.Writer, opts *slog.HandlerOptions) *commonHandler

NewCommonHandler creates a CommonHandler that writes to w, using the given options. If opts is nil, the default options are used. A [CommonHandler] is a low-level primitive for making structured log. NewGlogHandler or NewGlogHumanHandler recommended.

func NewRotateGlogHandler

func NewRotateGlogHandler(path string, opts *slog.HandlerOptions, options ...RotateOption) (slog.Handler, error)

NewRotateGlogHandler creates a GlogHandler that writes to rotate file, using the given options. If opts is nil, the default options are used. # LOG LINE PREFIX FORMAT

Log lines have this form:

Lyyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg...

where the fields are defined as follows:

L                A single character, representing the log level
                 (eg 'I' for INFO)
yyyy             The year
mm               The month (zero padded; ie May is '05')
dd               The day (zero padded)
hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
threadid         The space-padded thread ID as returned by GetTID()
                 (this matches the PID on Linux)
file             The file name
line             The line number
msg              The user-supplied message

Example:

I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395

func NewRotateGlogHumanHandler

func NewRotateGlogHumanHandler(path string, opts *slog.HandlerOptions, options ...RotateOption) (slog.Handler, error)

NewRotateGlogHumanHandler creates a human-readable GlogHandler that writes to rotate file, using the given options. If opts is nil, the default options are used. # LOG LINE PREFIX FORMAT

Log lines have this form:

[LLLLL] [yyyymmdd hh:mm:ss.uuuuuu] [threadid] [file:line(func)] msg...

where the fields are defined as follows:

LLLLL            Five characters, representing the log level
                 (eg 'INFO ' for INFO)
yyyy             The year
mm               The month (zero padded; ie May is '05')
dd               The day (zero padded)
hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
threadid         The space-padded thread ID as returned by GetTID()
                 (this matches the PID on Linux)
file             The file name
line             The line number
func             The func name
msg              The user-supplied message

Example:

[INFO] [1103 11:57:31.739339] [24395] [google.cc:2341] Command line: ./some_prog
[INFO] [1103 11:57:31.739403 24395] [google.cc:2342] Process id 24395

func NewRotateHandler

func NewRotateHandler(h NewHandler, path string, opts *slog.HandlerOptions, options ...RotateOption) (slog.Handler, error)

NewRotateHandler creates a slog.Handler that writes to rotate file, using the given options. If path is empty, the default os.Stdout are used. If opts is nil, the default options are used.

func NewRotateJSONHandler

func NewRotateJSONHandler(path string, opts *slog.HandlerOptions, options ...RotateOption) (slog.Handler, error)

NewRotateJSONHandler creates a JSONHandler that writes to rotate file, using the given options. If opts is nil, the default options are used.

func NewRotateTextHandler

func NewRotateTextHandler(path string, opts *slog.HandlerOptions, options ...RotateOption) (slog.Handler, error)

NewRotateTextHandler creates a TextHandler that writes to rotate file, using the given options. If opts is nil, the default options are used.

func ReplaceAttrTruncate

func ReplaceAttrTruncate(n int) func(groups []string, a slog.Attr) slog.Attr

ReplaceAttrTruncate returns [ReplaceAttr] which shrinks attr's key and value[string]'s len to n at most.

func ShortSource

func ShortSource(r slog.Record) *slog.Source

ShortSource 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.

Types

type EmptyRotateOption

type EmptyRotateOption struct{}

EmptyRotateOption does not alter the configuration. It can be embedded in another structure to build custom options.

This API is EXPERIMENTAL.

type GlogHandler

type GlogHandler struct {
	// contains filtered or unexported fields
}

func NewGlogHandler

func NewGlogHandler(w io.Writer, opts *slog.HandlerOptions) *GlogHandler

NewGlogHandler creates a GlogHandler that writes to w, using the given options. If opts is nil, the default options are used. # LOG LINE PREFIX FORMAT

Log lines have this form:

Lyyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg...

where the fields are defined as follows:

L                A single character, representing the log level
                 (eg 'I' for INFO)
yyyy             The year
mm               The month (zero padded; ie May is '05')
dd               The day (zero padded)
hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
threadid         The space-padded thread ID as returned by GetTID()
                 (this matches the PID on Linux)
file             The file name
line             The line number
msg              The user-supplied message

Example:

I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395

func NewGlogHumanHandler

func NewGlogHumanHandler(w io.Writer, opts *slog.HandlerOptions) *GlogHandler

NewGlogHumanHandler creates a human-readable GlogHandler that writes to w, using the given options. If opts is nil, the default options are used. # LOG LINE PREFIX FORMAT

Log lines have this form:

[LLLLL] [yyyymmdd hh:mm:ss.uuuuuu] [threadid] [file:line(func)] msg...

where the fields are defined as follows:

LLLLL            Five characters, representing the log level
                 (eg 'INFO ' for INFO)
yyyy             The year
mm               The month (zero padded; ie May is '05')
dd               The day (zero padded)
hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
threadid         The space-padded thread ID as returned by GetTID()
                 (this matches the PID on Linux)
file             The file name
line             The line number
func             The func name
msg              The user-supplied message

Example:

[INFO] [1103 11:57:31.739339] [24395] [google.cc:2341] Command line: ./some_prog
[INFO] [1103 11:57:31.739403 24395] [google.cc:2342] Process id 24395

func (*GlogHandler) Enabled

func (h *GlogHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

func (*GlogHandler) Handle

func (h *GlogHandler) Handle(_ context.Context, r slog.Record) error

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 GlogDate.

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.

Header formats a log header as defined by the C++ implementation. It returns a buffer containing the formatted header and the user's file and line number. The depth specifies how many stack frames above lives the source line to be identified in the log message.

LOG LINE PREFIX FORMAT

Log lines have this form:

Lyyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg...

where the fields are defined as follows:

L                A single character, representing the log level
                 (eg 'I' for INFO)
yyyy             The year
mm               The month (zero padded; ie May is '05')
dd               The day (zero padded)
hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
threadid         The space-padded thread ID as returned by GetTID()
                 (this matches the PID on Linux)
file             The file name
line             The line number
msg              The user-supplied message

Example:

I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395

NOTE: although the microseconds are useful for comparing events on a single machine, clocks on different machines may not be well synchronized. Hence, use caution when comparing the low bits of timestamps from different machines.

func (*GlogHandler) WithAttrs

func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new GlogHandler whose attributes consists of h's attributes followed by attrs.

func (*GlogHandler) WithGroup

func (h *GlogHandler) WithGroup(name string) slog.Handler

type NewHandler

type NewHandler func(w io.Writer, opts *slog.HandlerOptions) slog.Handler

NewHandler creates a slog.Handler that writes to w, using the given options. If opts is nil, the default options are used.

type ReplaceAttrKeys

type ReplaceAttrKeys map[string]string

ReplaceAttrKeys allows customization of the key names for default fields.

type RotateOption

type RotateOption interface {
	// contains filtered or unexported methods
}

A RotateOption sets options.

func WithRotateFileLinkPath

func WithRotateFileLinkPath(v string) RotateOption

WithRotateFileLinkPath sets FileLinkPath in rotate. sets the symbolic link name that gets linked to the current file name being used.

func WithRotateFilePathRotateLayout

func WithRotateFilePathRotateLayout(v string) RotateOption

WithRotateFilePathRotateLayout sets FilePathRotateLayout in rotate. Time layout to format rotate file

func WithRotateFilePathRotateStrftime

func WithRotateFilePathRotateStrftime(layout string) RotateOption

WithRotateFilePathRotateStrftime sets time layout in strftime format to format rotate file.

func WithRotateForceNewFileOnStartup

func WithRotateForceNewFileOnStartup(v bool) RotateOption

WithRotateForceNewFileOnStartup sets ForceNewFileOnStartup in rotate. Force File Rotate when start up

func WithRotateMaxAge

func WithRotateMaxAge(v time.Duration) RotateOption

WithRotateMaxAge sets MaxAge in rotate. max age of a log file before it gets purged from the file system. Remove rotated logs older than duration. The age is only checked if the file is to be rotated. take effects if only MaxAge is bigger than 0.

func WithRotateMaxCount

func WithRotateMaxCount(v int) RotateOption

WithRotateMaxCount sets MaxCount in rotate. Rotate files are rotated MaxCount times before being removed take effects if only MaxCount is bigger than 0.

func WithRotateRotateInterval

func WithRotateRotateInterval(v time.Duration) RotateOption

WithRotateRotateInterval sets RotateInterval in rotate. Rotate files are rotated until RotateInterval expired before being removed take effects if only RotateInterval is bigger than 0.

func WithRotateRotateSize

func WithRotateRotateSize(v int64) RotateOption

WithRotateRotateSize sets RotateSize in rotate. Rotate files are rotated if they grow bigger then size bytes. take effects if only RotateSize is bigger than 0.

type RotateOptionFunc

type RotateOptionFunc func(*rotate)

RotateOptionFunc wraps a function that modifies rotate into an implementation of the RotateOption interface.

type TimestampMode

type TimestampMode int
const (

	// DisableTimestamp disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp TimestampMode

	// SinceStartTimestamp enable the time passed since beginning of execution instead of
	// logging the full timestamp when a TTY is attached.
	SinceStartTimestamp
)

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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