logging

package
v0.0.0-...-da95e70 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2025 License: Apache-2.0 Imports: 6 Imported by: 779

Documentation

Overview

Package logging defines Logger interface and context.Context helpers to put\get logger from context.Context.

Unfortunately standard library doesn't define any Logger interface (only struct). And even worse: GAE logger is exposing different set of methods. Some additional layer is needed to unify the logging. Package logging is intended to be used from packages that support both local and GAE environments. Such packages should not use global logger but must accept instances of Logger interface (or even more generally context.Context) as parameters. Then callers can pass appropriate Logger implementation (or inject appropriate logger into context.Context) depending on where the code is running.

Index

Constants

View Source
const DefaultLevel = Info

DefaultLevel is the default Level value.

View Source
const (
	// ErrorKey is a logging field key to use for errors.
	ErrorKey = "error"
)

Variables

This section is empty.

Functions

func Debugf

func Debugf(ctx context.Context, fmt string, args ...any)

Debugf is a shorthand method to call the current logger's Errorf method.

func ErrorWithStackTrace

func ErrorWithStackTrace(ctx context.Context, stack StackTrace, fmt string, args ...any)

ErrorWithStackTrace submits an error with a stack trace associated with it.

func Errorf

func Errorf(ctx context.Context, fmt string, args ...any)

Errorf is a shorthand method to call the current logger's Errorf method.

func Infof

func Infof(ctx context.Context, fmt string, args ...any)

Infof is a shorthand method to call the current logger's Errorf method.

func IsLogging

func IsLogging(ctx context.Context, l Level) bool

IsLogging tests whether the context is configured to log at the specified level.

Individual Logger implementations are supposed to call this function when deciding whether to log the message.

func Logf

func Logf(ctx context.Context, l Level, fmt string, args ...any)

Logf is a shorthand method to call the current logger's logging method which corresponds to the supplied log level.

func SetError

func SetError(ctx context.Context, err error) context.Context

SetError returns a context with its error field set.

func SetFactory

func SetFactory(ctx context.Context, f Factory) context.Context

SetFactory sets the Logger factory for this context.

The factory will be called each time Get(context) is used.

func SetField

func SetField(ctx context.Context, key string, value any) context.Context

SetField is a convenience method for SetFields for a single key/value pair.

func SetFields

func SetFields(ctx context.Context, fields Fields) context.Context

SetFields adds the additional fields as context for the current Logger. The display of these fields depends on the implementation of the Logger. The new context will contain the combination of its current Fields, updated with the new ones (see Fields.Copy).

func SetLevel

func SetLevel(ctx context.Context, l Level) context.Context

SetLevel returns a new context with the given logging level.

It can be retrieved with GetLevel(context).

func SetStackTrace

func SetStackTrace(ctx context.Context, stack StackTrace) context.Context

SetStackTrace returns a new context with the given stack trace set in it.

All messages logged through it will be associated with this stack trace. This must be a stack trace in a format compatible with what is produced by https://pkg.go.dev/runtime/debug#Stack.

This is an advanced function. If you just want to log an error with a stack trace attached, use

func Warningf

func Warningf(ctx context.Context, fmt string, args ...any)

Warningf is a shorthand method to call the current logger's Errorf method.

Types

type Config

type Config struct {
	Level Level
}

Config is a logging configuration structure.

func (*Config) AddFlags

func (c *Config) AddFlags(fs *flag.FlagSet)

AddFlags adds common flags to a supplied FlagSet.

func (*Config) AddFlagsPrefix

func (c *Config) AddFlagsPrefix(fs *flag.FlagSet, prefix string)

AddFlagsPrefix adds common flags to a supplied FlagSet with a prefix.

A string prefix must be supplied which will be prepended to each added flag verbatim.

func (*Config) Set

func (c *Config) Set(ctx context.Context) context.Context

Set returns a new context configured to use logging level passed via the command-line level flag.

type Factory

type Factory func(context.Context, *LogContext) Logger

Factory returns a Logger instance bound to the specified log context.

func GetFactory

func GetFactory(ctx context.Context) Factory

GetFactory returns the currently-configured logging factory (or nil).

type FieldEntry

type FieldEntry struct {
	Key   string // The field's key.
	Value any    // The field's value.
}

FieldEntry is a static representation of a single key/value entry in a Fields.

func (*FieldEntry) String

func (e *FieldEntry) String() string

String returns the string representation of the field entry: "<key>":"<value>".

type Fields

type Fields map[string]any

Fields maps string keys to arbitrary values.

Fields can be added to a Context. Fields added to a Context augment those in the Context's parent Context, overriding duplicate keys. When Fields are added to a Context, they are copied internally for retention.

Fields can also be added directly to a log message by calling its logging passthrough methods. This immediate usage avoids the overhead of duplicating the fields for retention.

func GetFields

func GetFields(ctx context.Context) Fields

GetFields returns the current Fields.

This method is used for logger implementations with the understanding that the returned fields must not be mutated.

func NewFields

func NewFields(v map[string]any) Fields

NewFields instantiates a new Fields instance by duplicating the supplied map.

func WithError

func WithError(err error) Fields

WithError returns a Fields instance containing an error.

func (Fields) Copy

func (f Fields) Copy(other Fields) Fields

Copy returns a copy of this Fields with the keys from other overlaid on top of this one's.

func (Fields) Debugf

func (f Fields) Debugf(ctx context.Context, fmt string, args ...any)

Debugf is a shorthand method to call the current logger's Errorf method.

func (Fields) Errorf

func (f Fields) Errorf(ctx context.Context, fmt string, args ...any)

Errorf is a shorthand method to call the current logger's Errorf method.

func (Fields) Infof

func (f Fields) Infof(ctx context.Context, fmt string, args ...any)

Infof is a shorthand method to call the current logger's Errorf method.

func (Fields) SortedEntries

func (f Fields) SortedEntries() (s []*FieldEntry)

SortedEntries processes a Fields object, pruning invisible fields, placing the ErrorKey field first, and then sorting the remaining fields by key.

func (Fields) String

func (f Fields) String() string

String returns a string describing the contents of f in a sorted, dictionary-like format.

func (Fields) Warningf

func (f Fields) Warningf(ctx context.Context, fmt string, args ...any)

Warningf is a shorthand method to call the current logger's Errorf method.

type Level

type Level int

Level is an enumeration consisting of supported log levels.

const (
	Debug Level = iota
	Info
	Warning
	Error
)

Defined log levels.

func GetLevel

func GetLevel(ctx context.Context) Level

GetLevel returns the Level for this context. It will return DefaultLevel if none is defined.

func (*Level) Set

func (l *Level) Set(v string) error

Set implements flag.Value.

func (Level) String

func (l Level) String() string

String implements flag.Value.

type LogContext

type LogContext struct {
	// Factory can instantiate loggers configured to use this context.
	//
	// Used to construct Loggers when logging a message.
	Factory Factory

	// Level is the current logging level.
	//
	// Logging messages below this level will be silently discarded.
	Level Level

	// Fields is the current fields put into all messages.
	//
	// Details of how fields are logged depend on a particular logger
	// implementation.
	Fields Fields

	// StackTrace is a stack trace to associate with messages (if any).
	//
	// This is usually set only when logging messages that explicitly have a stack
	// trace attached (e.g. panic messages). Normally (e.g. when logging info
	// level messages) this will not be set. It's logging library user's
	// responsibility to capture this stack trace and associate it was a logging
	// message via ErrorWithStackTrace.
	StackTrace StackTrace
}

LogContext is the current logging context: the logging level, logging fields, etc.

It is propagated through context.Context. It is primarily used by logging handlers. Callers usually use functions like SetLevel to modify it.

Values of LogContext are immutable once constructed.

func CurrentLogContext

func CurrentLogContext(ctx context.Context) LogContext

CurrentLogContext returns a copy of the current LogContext in its entirety.

type Logger

type Logger interface {
	// Debugf formats its arguments according to the format, analogous to
	// fmt.Printf and records the text as a log message at Debug level.
	Debugf(format string, args ...any)

	// Infof is like Debugf, but logs at Info level.
	Infof(format string, args ...any)

	// Warningf is like Debugf, but logs at Warning level.
	Warningf(format string, args ...any)

	// Errorf is like Debugf, but logs at Error level.
	Errorf(format string, args ...any)

	// LogCall is a generic logging function. This is oriented more towards
	// utility functions than direct end-user usage.
	LogCall(l Level, calldepth int, format string, args []any)
}

Logger interface is ultimately implemented by underlying logging libraries (like go-logging or GAE logging). It is the least common denominator among logger implementations.

Logger instance is bound to some particular LogContext that defines logging level and extra message fields.

Implementations register factories that produce Loggers (using 'SetFactory' function), and top level functions (like 'Infof') use them to grab instances of Logger bound to passed contexts. That's how they know what logging level to use and what extra fields to add.

var Null Logger = nullLogger{}

Null is a logger that silently ignores all messages.

func Get

func Get(ctx context.Context) Logger

Get the current Logger, or a logger that ignores all messages if none is defined.

type StackTrace

type StackTrace struct {
	// Standard is a stack trace in a standard format compatible with what is
	// produced by https://pkg.go.dev/runtime/debug#Stack
	//
	// This must be a stack trace of a single goroutine. This format is used when
	// pushing the stack trace to Cloud Error Reporting or similar services that
	// can aggregate errors by where they happened.
	Standard string

	// Textual is a stack trace in an arbitrary human-readable format for output
	// in text logs.
	//
	// This can have arbitrary format as long as the information here is useful
	// to show in text logs. This trace will be appended to the logging message
	// when logging to a human-readable log.
	//
	// If empty, defaults to Standard.
	Textual string
}

StackTrace is a representation of a stack trace where an error happened.

func (StackTrace) ForTextLog

func (s StackTrace) ForTextLog() string

ForTextLog returns either s.Textual (if set) or s.Standard.

Directories

Path Synopsis
Package errlogger implements a logger that logs errors to Cloud Error Reporting service.
Package errlogger implements a logger that logs errors to Cloud Error Reporting service.
Package gologger is a compatibility layer between go-logging library and luci-go/common/logging.
Package gologger is a compatibility layer between go-logging library and luci-go/common/logging.
Package sdlogger is a logger that formats entries as JSON understood by Stackdriver log collectors.
Package sdlogger is a logger that formats entries as JSON understood by Stackdriver log collectors.
Package teelogger implements a logger that splits messages across multiple different loggers.
Package teelogger implements a logger that splits messages across multiple different loggers.

Jump to

Keyboard shortcuts

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