slog

package
v1.2.115 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2024 License: MIT Imports: 26 Imported by: 3

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.

Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

// ...
{
	fmt.Printf("----text----\n")
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
	logger.Info("text message")
}
// ...
{
	fmt.Printf("----json----\n")
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
	logger.Info("json message")
}
// ...
{
	fmt.Printf("----glog----\n")
	logger := slog.New(NewGlogHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
	logger.Info("glog message")
}
// ...
{
	fmt.Printf("----glog_human----\n")
	logger := slog.New(NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
	logger.Info("glog_human message")
}
// ...
{
	fmt.Printf("----multi[text-json-glog-glog_human]----\n")
	logger := slog.New(MultiHandler(
		slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}),
		slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}),
		NewGlogHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}),
		NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}),
	))
	logger.Info("multi[text-json-glog-glog_human] message")
}
Output:

----text----
level=INFO msg="text message"
----json----
{"level":"INFO","msg":"json message"}
----glog----
I 0] glog message
----glog_human----
[INFO ] [0] glog_human message
----multi[text-json-glog-glog_human]----
level=INFO msg="multi[text-json-glog-glog_human] message"
{"level":"INFO","msg":"multi[text-json-glog-glog_human] message"}
I 0] multi[text-json-glog-glog_human] message
[INFO ] [0] multi[text-json-glog-glog_human] message

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
Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

path := "" // If path is empty, the default os.Stdout are used. path can be relative path or absolute path.
var slogOpt slog.HandlerOptions
slogOpt.ReplaceAttr = slogtest.RemoveTime

// if set: path = /tmp/logs/slog.log
// slog.log -> /tmp/logs/slog.20240202180000.log
// /tmp/logs/slog.20240202170000.log
// /tmp/logs/slog.20240202180000.log
// ...
rotateOpts := []RotateOption{
	WithRotateRotateInterval(time.Hour),
	WithRotateMaxCount(3),
	WithRotateMaxAge(24 * time.Hour),
	// Below is default options.
	// WithRotateFilePathRotateStrftime(".%Y%m%d%H%M%S.log"), // time layout in strftime format to format rotate file.
	// WithRotateFilePathRotateLayout(".20060102150405.log"), // time layout in golang format to format rotate file.
	// WithRotateFileLinkPath(filepath.Base(path) + ".log"), // the symbolic link name that gets linked to the current file name being used.
}
// ...
{
	fmt.Printf("----rotate_glog----\n")
	handler, err := NewRotateGlogHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate glog handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate glog message")
}
Output:

----rotate_glog----
I 0] rotate glog message

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
Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

path := "" // If path is empty, the default os.Stdout are used. path can be relative path or absolute path.
var slogOpt slog.HandlerOptions
slogOpt.ReplaceAttr = slogtest.RemoveTime

// if set: path = /tmp/logs/slog.log
// slog.log -> /tmp/logs/slog.20240202180000.log
// /tmp/logs/slog.20240202170000.log
// /tmp/logs/slog.20240202180000.log
// ...
rotateOpts := []RotateOption{
	WithRotateRotateInterval(time.Hour),
	WithRotateMaxCount(3),
	WithRotateMaxAge(24 * time.Hour),
	// Below is default options.
	// WithRotateFilePathRotateStrftime(".%Y%m%d%H%M%S.log"), // time layout in strftime format to format rotate file.
	// WithRotateFilePathRotateLayout(".20060102150405.log"), // time layout in golang format to format rotate file.
	// WithRotateFileLinkPath(filepath.Base(path) + ".log"), // the symbolic link name that gets linked to the current file name being used.
}
// ...
{
	fmt.Printf("----rotate_glog_human----\n")
	handler, err := NewRotateGlogHumanHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate human glog handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate glog_human message")
}
Output:

----rotate_glog_human----
[INFO ] [0] rotate glog_human message

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.

Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

path := "" // If path is empty, the default os.Stdout are used. path can be relative path or absolute path.
var slogOpt slog.HandlerOptions
slogOpt.ReplaceAttr = slogtest.RemoveTime

// if set: path = /tmp/logs/slog.log
// slog.log -> /tmp/logs/slog.20240202180000.log
// /tmp/logs/slog.20240202170000.log
// /tmp/logs/slog.20240202180000.log
// ...
rotateOpts := []RotateOption{
	WithRotateRotateInterval(time.Hour),
	WithRotateMaxCount(3),
	WithRotateMaxAge(24 * time.Hour),
	// Below is default options.
	// WithRotateFilePathRotateStrftime(".%Y%m%d%H%M%S.log"), // time layout in strftime format to format rotate file.
	// WithRotateFilePathRotateLayout(".20060102150405.log"), // time layout in golang format to format rotate file.
	// WithRotateFileLinkPath(filepath.Base(path) + ".log"), // the symbolic link name that gets linked to the current file name being used.
}
// ...
{
	fmt.Printf("----rotate_text----\n")
	handler, err := NewRotateTextHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate text handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate text message")
}
// ...
{
	fmt.Printf("----rotate_json----\n")
	handler, err := NewRotateJSONHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate json handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate json message")
}
// ...
{
	fmt.Printf("----rotate_glog----\n")
	handler, err := NewRotateGlogHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate glog handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate glog message")
}
// ...
{
	fmt.Printf("----rotate_glog_human----\n")
	handler, err := NewRotateGlogHumanHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate human glog handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate glog_human message")
}
// ...
{
	fmt.Printf("----multi_rotate[text-json-glog-glog_human]----\n")
	logger := slog.New(MultiHandler(
		func() slog.Handler {
			handler, err := NewRotateTextHandler(path,
				&slogOpt, // If opts is nil, the default options are used.
				rotateOpts...)
			if err != nil {
				panic("failed to create rotate text handler:" + err.Error())
			}
			return handler
		}(),
		func() slog.Handler {
			handler, err := NewRotateJSONHandler(path,
				&slogOpt, // If opts is nil, the default options are used.
				rotateOpts...)
			if err != nil {
				panic("failed to create rotate json handler:" + err.Error())
			}
			return handler
		}(),
		func() slog.Handler {
			handler, err := NewRotateGlogHandler(path,
				&slogOpt, // If opts is nil, the default options are used.
				rotateOpts...)
			if err != nil {
				panic("failed to create rotate glog handler:" + err.Error())
			}
			return handler
		}(),
		func() slog.Handler {
			handler, err := NewRotateGlogHumanHandler(path,
				&slogOpt, // If opts is nil, the default options are used.
				rotateOpts...)
			if err != nil {
				panic("failed to create rotate glog_human handler:" + err.Error())
			}
			return handler
		}(),
	))
	logger.Info("rotate multi_rotate[text-json-glog-glog_human] message")
}
Output:

----rotate_text----
level=INFO msg="rotate text message"
----rotate_json----
{"level":"INFO","msg":"rotate json message"}
----rotate_glog----
I 0] rotate glog message
----rotate_glog_human----
[INFO ] [0] rotate glog_human message
----multi_rotate[text-json-glog-glog_human]----
level=INFO msg="rotate multi_rotate[text-json-glog-glog_human] message"
{"level":"INFO","msg":"rotate multi_rotate[text-json-glog-glog_human] message"}
I 0] rotate multi_rotate[text-json-glog-glog_human] message
[INFO ] [0] rotate multi_rotate[text-json-glog-glog_human] message

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.

Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

path := "" // If path is empty, the default os.Stdout are used. path can be relative path or absolute path.
var slogOpt slog.HandlerOptions
slogOpt.ReplaceAttr = slogtest.RemoveTime

// if set: path = /tmp/logs/slog.log
// slog.log -> /tmp/logs/slog.20240202180000.log
// /tmp/logs/slog.20240202170000.log
// /tmp/logs/slog.20240202180000.log
// ...
rotateOpts := []RotateOption{
	WithRotateRotateInterval(time.Hour),
	WithRotateMaxCount(3),
	WithRotateMaxAge(24 * time.Hour),
	// Below is default options.
	// WithRotateFilePathRotateStrftime(".%Y%m%d%H%M%S.log"), // time layout in strftime format to format rotate file.
	// WithRotateFilePathRotateLayout(".20060102150405.log"), // time layout in golang format to format rotate file.
	// WithRotateFileLinkPath(filepath.Base(path) + ".log"), // the symbolic link name that gets linked to the current file name being used.
}
// ...
{
	fmt.Printf("----rotate_json----\n")
	handler, err := NewRotateJSONHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate json handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate json message")
}
Output:

----rotate_json----
{"level":"INFO","msg":"rotate json message"}

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.

Example
getPid = func() int { return 0 } // set pid to zero for test
defer func() { getPid = os.Getpid }()

path := "" // If path is empty, the default os.Stdout are used. path can be relative path or absolute path.
var slogOpt slog.HandlerOptions
slogOpt.ReplaceAttr = slogtest.RemoveTime

// if set: path = /tmp/logs/slog.log
// slog.log -> /tmp/logs/slog.20240202180000.log
// /tmp/logs/slog.20240202170000.log
// /tmp/logs/slog.20240202180000.log
// ...
rotateOpts := []RotateOption{
	WithRotateRotateInterval(time.Hour),
	WithRotateMaxCount(3),
	WithRotateMaxAge(24 * time.Hour),
	// Below is default options.
	// WithRotateFilePathRotateStrftime(".%Y%m%d%H%M%S.log"), // time layout in strftime format to format rotate file.
	// WithRotateFilePathRotateLayout(".20060102150405.log"), // time layout in golang format to format rotate file.
	// WithRotateFileLinkPath(filepath.Base(path) + ".log"), // the symbolic link name that gets linked to the current file name being used.
}
// ...
{
	fmt.Printf("----rotate_text----\n")
	handler, err := NewRotateTextHandler(path,
		&slogOpt, // If opts is nil, the default options are used.
		rotateOpts...)
	if err != nil {
		panic("failed to create rotate text handler:" + err.Error())
	}
	logger := slog.New(handler)
	logger.Info("rotate text message")
}
Output:

----rotate_text----
level=INFO msg="rotate text message"

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