log

package module
v0.0.0-...-a672c30 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2025 License: MIT Imports: 24 Imported by: 0

README

log

This structured logging library is developed with reference to Go's standard log/slog package. Although slog provides a solid foundation for structured logging, it does not support delayed field loading with the With method, resulting in premature evaluation of dynamic values. This reduces flexibility and efficiency in scenarios where log attributes—such as timestamps, request IDs, or metrics—require runtime computation. To address this, we rewrote this library.

Install

go get github.com/nexuer/log

Performance

After benchmarking, the overall performance is comparable to that of slog.

Benchmarks

Documentation

Index

Constants

View Source
const (
	// LevelKey is the key used by the built-in handlers for the level
	// of the log call.
	LevelKey = "level"
	// MessageKey is the key used by the built-in handlers for the
	// message of the log call. The associated value is a string.
	MessageKey = "msg"
	// NameKey is the key used by the built-in handlers for the logger name.
	NameKey = "logger"
	// ErrKey is the key used by the built-in handlers for the error message.
	ErrKey = "err"
)

Keys for "built-in" attributes.

Variables

View Source
var (
	// DefaultCaller is a Valuer that returns the file and line.
	DefaultCaller = Caller(7)

	// DefaultTimestamp is a Valuer that returns the current wallclock time.
	DefaultTimestamp = Timestamp(time.RFC3339)

	DefaultFields = []any{
		"ts", DefaultTimestamp,
		"caller", DefaultCaller,
	}
)
View Source
var Discard = writerWrapper{Writer: io.Discard}
View Source
var (
	// ErrorHandler is called whenever fails to write an event on its
	// output. default an error is printed on the stderr. This handler must
	// be thread safe and non-blocking.
	ErrorHandler func(err error) = func(err error) {
		_, _ = fmt.Fprintf(os.Stderr, "log: write failed, %v\n", err)
	}
)

Functions

func AddFlags

func AddFlags(fs *flag.FlagSet)

func Close

func Close() error

func Debug

func Debug(args ...any)

Debug logs a message at debug level.

func DebugS

func DebugS(msg string, kvs ...any)

DebugS logs a message at debug level with key vals.

func Debugf

func Debugf(format string, args ...any)

Debugf logs a message at debug level.

func Error

func Error(args ...any)

Error logs a message at error level.

func ErrorS

func ErrorS(err error, msg string, kvs ...any)

ErrorS logs a message at error level with key vals.

func Errorf

func Errorf(format string, args ...any)

Errorf logs a message at error level.

func Fatal

func Fatal(args ...any)

Fatal logs a message at fatal level.

func FatalS

func FatalS(err error, msg string, kvs ...any)

FatalS logs a message at fatal level with key vals.

func Fatalf

func Fatalf(format string, args ...any)

Fatalf logs a message at fatal level.

func FileWriter

func FileWriter(path string, size int64, backups int64, compress ...bool) io.Writer

func Info

func Info(args ...any)

Info logs a message at info level.

func InfoS

func InfoS(msg string, kvs ...any)

InfoS logs a message at info level with key vals.

func Infof

func Infof(format string, args ...any)

Infof logs a message at info level.

func MultiWriter

func MultiWriter(writers ...io.Writer) io.Writer

MultiWriter creates a writer that duplicates its writes to all the provided writers, 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 SetDefault

func SetDefault(l *Logger)

SetDefault makes l the default Logger, which is used by the top-level functions Info, Debug and so on.

func TryMultiWriter

func TryMultiWriter(strategy ByteCountStrategy, writers ...io.Writer) io.Writer

TryMultiWriter creates a writer that attempts to write to all provided io.Writers. The first argument specifies the byte count strategy, which determines how the returned byte count is calculated. It collects all errors and joins them with errors.Join.

func Warn

func Warn(args ...any)

Warn logs a message at warn level.

func WarnS

func WarnS(msg string, kvs ...any)

WarnS logs a message at warn level with key vals.

func Warnf

func Warnf(format string, args ...any)

Warnf logs a message at warn level.

func WithCallerDepth

func WithCallerDepth(ctx context.Context, depth int) context.Context

Types

type ByteCountStrategy

type ByteCountStrategy int

ByteCountStrategy defines the strategy for determining the number of bytes returned by Write.

const (
	// StrategyFirst returns the byte count from the first writer.
	StrategyFirst ByteCountStrategy = iota
	// StrategyMin returns the minimum byte count among writes.
	StrategyMin
	// StrategyMax returns the maximum byte count among writes.
	StrategyMax
)

type Config

type Config struct {
	Format   Format
	Level    Level
	Output   Output
	File     FileConfig
	Replacer Replacer
}

type Field

type Field struct {
	Key   string
	Value Value
}

func Any

func Any(key string, value any) Field

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

func Bool

func Bool(key string, v bool) Field

Bool returns an Attr for a bool.

func Duration

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

Duration returns an Attr for a time.Duration.

func Float64

func Float64(key string, v float64) Field

Float64 returns a Field for a floating-point number.

func Group

func Group(key string, kvs ...any) Field

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) Field

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

func Int64

func Int64(key string, value int64) Field

Int64 returns a Field for an int64.

func String

func String(key, value string) Field

String returns an Attr for a string value.

func Time

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

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

func Uint64

func Uint64(key string, v uint64) Field

Uint64 returns a Field for a uint64.

func (Field) Equal

func (f Field) Equal(b Field) bool

Equal reports whether a and b have equal keys and values.

func (Field) String

func (f Field) String() string

type FileConfig

type FileConfig struct {
	Dir      string
	Size     int64
	Backups  int64
	Compress bool
}

type Format

type Format int
const (
	TextFormat Format = iota
	JsonFormat
)

type Handler

type Handler interface {
	WithFields(ctx context.Context, fields ...Field) Handler

	// Handle handles the Log with Context, Writer, Level , Message and the arguments.
	Handle(ctx context.Context, w io.Writer, level Level, msg string, kvs ...any) error
}

func Json

func Json(opts ...*HandlerOptions) Handler

func Text

func Text(opts ...*HandlerOptions) Handler

type HandlerOptions

type HandlerOptions struct {
	Name     string
	Replacer Replacer
}

type Kind

type Kind int

Kind is the kind of a Value.

const (
	KindAny Kind = iota
	KindBool
	KindDuration
	KindFloat64
	KindInt64
	KindString
	KindTime
	KindUint64
	KindGroup

	// KindValuer Use KindValuer instead of slog.kindLogValuer
	KindValuer
	KindSource
)

func (Kind) String

func (k Kind) String() string

type Level

type Level int

Level is a logger level.

const (
	LevelDebug Level = -4
	LevelInfo  Level = 0
	LevelWarn  Level = 4
	LevelError Level = 8
	LevelFatal Level = 12
)

func ParseLevel

func ParseLevel(s string) Level

func (Level) Enable

func (l Level) Enable(level Level) bool

func (Level) String

func (l Level) String() string

type Logger

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

func Default

func Default() *Logger

Default returns the default Logger.

func New

func New(w io.Writer, h ...Handler) *Logger

func (*Logger) Close

func (l *Logger) Close() error

func (*Logger) Context

func (l *Logger) Context() context.Context

func (*Logger) Debug

func (l *Logger) Debug(args ...any)

Debug logs a message at debug level.

func (*Logger) DebugS

func (l *Logger) DebugS(msg string, kvs ...any)

DebugS logs a message at debug level with key vals.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...any)

Debugf logs a message at debug level.

func (*Logger) Error

func (l *Logger) Error(args ...any)

Error logs a message at error level.

func (*Logger) ErrorS

func (l *Logger) ErrorS(err error, msg string, kvs ...any)

ErrorS logs a message at error level with key vals.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...any)

Errorf logs a message at warn level.

func (*Logger) Fatal

func (l *Logger) Fatal(args ...any)

Fatal logs a message at fatal level.

func (*Logger) FatalS

func (l *Logger) FatalS(err error, msg string, kvs ...any)

FatalS logs a message at fatal level with key vals.

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...any)

Fatalf logs a message at warn level.

func (*Logger) Handle

func (l *Logger) Handle(ctx context.Context, w io.Writer, level Level, msg string, kvs ...any) error

func (*Logger) Info

func (l *Logger) Info(args ...any)

Info logs a message at info level.

func (*Logger) InfoS

func (l *Logger) InfoS(msg string, kvs ...any)

InfoS logs a message at info level with key vals.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...any)

Infof logs a message at info level.

func (*Logger) Log

func (l *Logger) Log(ctx context.Context, level Level, msg string, kvs ...any) error

func (*Logger) SetHandler

func (l *Logger) SetHandler(h Handler) *Logger

SetHandler set the current Handler Note: This is not concurrency-safe.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level) *Logger

SetLevel set the current minimum severity level for logging output. Note: This is not concurrency-safe.

func (*Logger) SetOutput

func (l *Logger) SetOutput(w io.Writer) *Logger

SetOutput set the current io.Writer Note: This is not concurrency-safe.

func (*Logger) Warn

func (l *Logger) Warn(args ...any)

Warn logs a message at warn level.

func (*Logger) WarnS

func (l *Logger) WarnS(msg string, kvs ...any)

WarnS logs a message at warn level with key vals.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...any)

Warnf logs a message at warn level.

func (*Logger) With

func (l *Logger) With(kvs ...any) *Logger

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

func (*Logger) WithFields

func (l *Logger) WithFields(fields ...Field) *Logger

func (*Logger) Write

func (l *Logger) Write(p []byte) (n int, err error)

func (*Logger) Writer

func (l *Logger) Writer() io.Writer

type Manager

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

func InitManager

func InitManager(name string, fields ...any) *Manager

InitManager init global manager

func M

func M() *Manager

func NewManager

func NewManager(name string, kvs ...any) *Manager

func (*Manager) Add

func (m *Manager) Add(name string, kvs ...any) (*Logger, error)

func (*Manager) AddWithSuffix

func (m *Manager) AddWithSuffix(suffix string, kvs ...any) (*Logger, error)

func (*Manager) Apply

func (m *Manager) Apply(cfg Config) Config

func (*Manager) Close

func (m *Manager) Close() error

func (*Manager) Logger

func (m *Manager) Logger(name ...string) *Logger

type Output

type Output int
const (
	StderrOutput Output = iota
	StdoutOutput
	FileOutput
)

type Readonly

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

Readonly is a logger wrapper that restricts modifications to the underlying logger. It prevents changes to log configuration, such as altering the log level or output, and excludes the Fatal level to avoid program termination. All methods delegate to the wrapped Logger, providing only logging output functionality.

func NewReadonly

func NewReadonly(log *Logger) *Readonly

NewReadonly creates a new Readonly logger, wrapping the provided Logger. If log is nil, it uses a default Logger from Default().

func (*Readonly) Debug

func (r *Readonly) Debug(args ...any)

func (*Readonly) Debugf

func (r *Readonly) Debugf(format string, args ...any)

func (*Readonly) Error

func (r *Readonly) Error(args ...any)

func (*Readonly) Errorf

func (r *Readonly) Errorf(format string, args ...any)

func (*Readonly) Info

func (r *Readonly) Info(args ...any)

func (*Readonly) Infof

func (r *Readonly) Infof(format string, args ...any)

func (*Readonly) Warn

func (r *Readonly) Warn(args ...any)

func (*Readonly) Warnf

func (r *Readonly) Warnf(format string, args ...any)

func (*Readonly) Write

func (r *Readonly) Write(p []byte) (int, error)

type Replacer

type Replacer func(ctx context.Context, groups []string, field Field) Field

Replacer transforms log fields to hide sensitive data or desensitize information.

type Source

type Source struct {
	// Function is the package path-qualified function name containing the
	// source line. If non-empty, this string uniquely identifies a single
	// function in the program. This may be the empty string if not known.
	Function string `json:"function"`
	// File and Line are the file name and line number (1-based) of the source
	// line. These may be the empty string and zero, respectively, if not known.
	File string `json:"file"`
	Line int    `json:"line"`
}

func (*Source) String

func (s *Source) String() string

type Value

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

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 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 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 ...Field) 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 ResolveValuer

func ResolveValuer(ctx context.Context, valuer Valuer) Value

func SourceValue

func SourceValue(v *Source) Value

SourceValue returns a Value for a Source.

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.

func UintValue

func UintValue(v uint) Value

UintValue returns a Value for an uint.

func ValuerValue

func ValuerValue(valuer Valuer) Value

ValuerValue return the function value on Valuer.

func (Value) Any

func (v Value) Any() any

Any returns v's value as an any.

func (Value) Bool

func (v Value) Bool() bool

Bool returns v's value as a bool. It panics if v is not a bool.

func (Value) Duration

func (v Value) Duration() time.Duration

Duration returns v's value as a time.Duration. It panics if v is not a time.Duration.

func (Value) Equal

func (v Value) Equal(w Value) bool

Equal reports whether v and w represent the same Go value.

func (Value) Float64

func (v Value) Float64() float64

Float64 returns v's value as a float64. It panics if v is not a float64.

func (Value) Group

func (v Value) Group() []Field

Group returns v's value as a []Attr. It panics if v's Kind is not KindGroup.

func (Value) Int64

func (v Value) Int64() int64

Int64 returns v's value as an int64. It panics if v is not a signed integer.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns v's Kind.

func (Value) Resolve

func (v Value) Resolve(ctx context.Context) (rv Value)

Resolve repeatedly calls Valuer on v while it implements Valuer, and returns the result. If v resolves to a group, the group's attributes' values are not recursively resolved. If the number of Valuer calls exceeds a threshold, a Value containing an error is returned. Resolve's return value is guaranteed not to be of Kind KindValuer.

func (Value) Source

func (v Value) Source() *Source

func (Value) String

func (v Value) String() string

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 (Value) Time

func (v Value) Time() time.Time

Time returns v's value as a time.Time. It panics if v is not a time.Time.

func (Value) Uint64

func (v Value) Uint64() uint64

Uint64 returns v's value as a uint64. It panics if v is not an unsigned integer.

func (Value) Valuer

func (v Value) Valuer() Valuer

Valuer returns v's value as a LogValuer. It panics if v is not a LogValuer.

type Valuer

type Valuer func(ctx context.Context) Value

func Caller

func Caller(depth int, full ...bool) Valuer

func Timestamp

func Timestamp(layout string) Valuer

func (Valuer) String

func (v Valuer) String() string

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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