log

package
v1.13.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2023 License: BSD-3-Clause Imports: 17 Imported by: 38

Documentation

Overview

Example
package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/ethersphere/bee/pkg/log"
)

func main() {
	log.ModifyDefaults(
		log.WithSink(os.Stdout),
		log.WithVerbosity(log.VerbosityAll),
	)

	logger := log.NewLogger("example").Build()
	logger.Error(nil, "error should work", "k", 1, "k", 2)
	logger.Warning("warning should work", "address", 12345)
	logger.Info("info should work", "k", 3, "k", 4)
	logger.Debug("debug should work", "error", errors.New("failed"))
	fmt.Println()

	loggerV1 := logger.V(1).Build()
	loggerV1.Error(nil, "v1 error should work")
	loggerV1.Warning("v1 warning should work")
	loggerV1.Info("v1 info should work")
	loggerV1.Debug("v1 debug should work")
	fmt.Println()

	_ = log.SetVerbosity(loggerV1, log.VerbosityWarning)
	loggerV1.Error(nil, "v1 error should work")
	loggerV1.Warning("v1 warning should work")
	loggerV1.Info("v1 info shouldn't work")
	loggerV1.Debug("v1 debug shouldn't work")
	fmt.Println()

	loggerV1WithName := loggerV1.WithName("example_name").Build()
	// The verbosity was inherited from loggerV1 so we have to change it.
	_ = log.SetVerbosity(loggerV1WithName, log.VerbosityAll)
	loggerV1WithName.Error(nil, "v1 with name error should work")
	loggerV1WithName.Warning("v1 with name warning should work")
	loggerV1WithName.Info("v1 with name info should work")
	loggerV1WithName.Debug("v1 with name debug should work")

}
Output:

"level"="error" "logger"="example" "msg"="error should work" "k"=1 "k"=2
"level"="warning" "logger"="example" "msg"="warning should work" "address"=12345
"level"="info" "logger"="example" "msg"="info should work" "k"=3 "k"=4
"level"="debug" "logger"="example" "msg"="debug should work" "error"="failed"

"level"="error" "logger"="example" "msg"="v1 error should work"
"level"="warning" "logger"="example" "msg"="v1 warning should work"
"level"="info" "logger"="example" "msg"="v1 info should work"
"level"="debug" "logger"="example" "v"=1 "msg"="v1 debug should work"

"level"="error" "logger"="example" "msg"="v1 error should work"
"level"="warning" "logger"="example" "msg"="v1 warning should work"

"level"="error" "logger"="example/example_name" "msg"="v1 with name error should work"
"level"="warning" "logger"="example/example_name" "msg"="v1 with name warning should work"
"level"="info" "logger"="example/example_name" "msg"="v1 with name info should work"
"level"="debug" "logger"="example/example_name" "v"=1 "msg"="v1 with name debug should work"

Index

Examples

Constants

View Source
const (
	// VerbosityNone will silence the logger.
	VerbosityNone = Level(iota - 4)
	// VerbosityError allows only error messages to be printed.
	VerbosityError
	// VerbosityWarning allows only error and warning messages to be printed.
	VerbosityWarning
	// VerbosityInfo allows only error, warning and info messages to be printed.
	VerbosityInfo
	// VerbosityDebug allows only error, warning, info and debug messages to be printed.
	VerbosityDebug
	// VerbosityAll allows to print all messages up to and including level V.
	// It is a placeholder for the maximum possible V level verbosity within the logger.
	VerbosityAll = Level(1<<31 - 1)
)

Variables

This section is empty.

Functions

func Lock

func Lock(w io.Writer) io.Writer

Lock wraps io.Writer in a mutex to make it safe for concurrent use. In particular, *os.Files must be locked before use.

func ModifyDefaults

func ModifyDefaults(opts ...Option)

ModifyDefaults modifies the global default options for this log package that each new logger inherits when it is created. The default values can be modified only once, so further calls to this function will be ignored. This function should be called before the first call to the NewLogger factory constructor, otherwise it will have no effect.

func RegistryIterate

func RegistryIterate(fn func(id, path string, verbosity Level, v uint) (next bool))

RegistryIterate iterates through all registered loggers.

func SetVerbosity

func SetVerbosity(l Logger, v Level) error

SetVerbosity sets the level of verbosity of the given logger.

func SetVerbosityByExp

func SetVerbosityByExp(e string, v Level) error

SetVerbosityByExp sets all loggers to the given verbosity level v that match the given expression e, which can be a logger id or a regular expression. An error is returned if e fails to compile.

Types

type Builder

type Builder interface {
	// V specifies verbosity level added to the debug verbosity, relative to
	// the parent Logger. In other words, V-levels are additive. A higher
	// verbosity level means a log message is less important.
	V(v uint) Builder

	// WithName specifies a name element added to the Logger's name.
	// Successive calls with WithName append additional suffixes to the
	// Logger's name. It's strongly recommended that name segments contain
	// only letters, digits, and hyphens (see the package documentation for
	// more information). Formatter uses '/' characters to separate name
	// elements. Callers should not pass '/' in the provided name string.
	WithName(name string) Builder

	// WithValues specifies additional key/value pairs
	// to be logged with each log line.
	WithValues(keysAndValues ...interface{}) Builder

	// Build returns a new or existing Logger
	// instance, if such instance already exists.
	// The new instance is not registered in the
	// logger registry.
	Build() Logger

	// Register returns new or existing Logger
	// instance, if such instance already exists.
	// If a new instance is created, it is also
	// registered in the logger registry.
	Register() Logger
}

Builder specifies a set of methods that can be used to modify the behavior of the logger before it is created.

type Hook

type Hook interface {
	Fire(Level) error
}

Hook that is fired when logging on the associated severity log level. Note, the call must be non-blocking.

type Level

type Level int32

Level specifies a level of verbosity for logger. Level should be modified only through its set method. Level is treated as a sync/atomic int32.

func MustParseVerbosityLevel added in v1.10.0

func MustParseVerbosityLevel(s string) Level

MustParseVerbosityLevel returns a verbosity Level parsed from the given s. It panics if the given s is not a valid verbosity level.

func ParseVerbosityLevel

func ParseVerbosityLevel(s string) (Level, error)

ParseVerbosityLevel returns a verbosity Level parsed from the given s.

func (Level) String

func (l Level) String() string

String implements the fmt.Stringer interface.

type Logger

type Logger interface {
	Builder

	// Verbosity returns the current verbosity level of this logger.
	Verbosity() Level

	// Debug logs a debug message with the given key/value pairs as context.
	// The msg argument should be used to add some constant description to
	// the log line. The key/value pairs can then be used to add additional
	// variable information. The key/value pairs must alternate string keys
	// and arbitrary values.
	Debug(msg string, keysAndValues ...interface{})

	// Info logs an info message with the given key/value pairs as context.
	// The msg argument should be used to add some constant description to
	// the log line. The key/value pairs can then be used to add additional
	// variable information. The key/value pairs must alternate string keys
	// and arbitrary values.
	Info(msg string, keysAndValues ...interface{})

	// Warning logs a warning message with the given key/value pairs as context.
	// The msg argument should be used to add some constant description to
	// the log line. The key/value pairs can then be used to add additional
	// variable information. The key/value pairs must alternate string keys
	// and arbitrary values.
	Warning(msg string, keysAndValues ...interface{})

	// Error logs an error, with the given message and key/value pairs as context.
	// The msg argument should be used to add context to any underlying error,
	// while the err argument should be used to attach the actual error that
	// triggered this log line, if present. The err parameter is optional
	// and nil may be passed instead of an error instance.
	Error(err error, msg string, keysAndValues ...interface{})
}

Logger provides a set of methods that define the behavior of the logger.

var Noop Logger = new(noopLogger)

Noop is an implementation of a logger that does not log.

func NewLogger

func NewLogger(name string, opts ...Option) Logger

NewLogger is a factory constructor which returns a new logger instance based on the given name. If such an instance already exists in the logger registry, then this existing instance is returned instead. The given options take precedence over the default options set by the ModifyDefaults function.

type Marshaler

type Marshaler interface {
	// MarshalLog can be used to:
	//   - ensure that structs are not logged as strings when the original
	//     value has a String method: return a different type without a
	//     String method
	//   - select which fields of a complex type should get logged:
	//     return a simpler struct with fewer fields
	//   - log unexported fields: return a different struct
	//     with exported fields
	//
	// It may return any value of any type.
	MarshalLog() interface{}
}

Marshaler is an optional interface that logged values may choose to implement. Loggers with structured output, such as JSON, should log the object return by the MarshalLog method instead of the original value.

type MessageCategory

type MessageCategory int

MessageCategory indicates which category or categories of messages should include the caller in the log lines.

const (
	CategoryNone MessageCategory = iota
	CategoryAll
	CategoryError
	CategoryWarning
	CategoryInfo
	CategoryDebug
)

type Option

type Option func(*Options)

Option represent Options parameters modifier.

func WithCaller

func WithCaller(category MessageCategory) Option

WithCaller tells the logger to add a "caller" key to some or all log lines. This has some overhead, so some users might not want it.

func WithCallerDepth

func WithCallerDepth(depth int) Option

WithCallerDepth tells the logger the number of stack-frames to skip when attributing the log line to a file and line.

func WithCallerFunc

func WithCallerFunc() Option

WithCallerFunc tells the logger to also log the calling function name. This has no effect if caller logging is not enabled (see WithCaller).

func WithJSONOutput

func WithJSONOutput() Option

WithJSONOutput tells the logger if the output should be formatted as JSON.

func WithLevelHooks

func WithLevelHooks(l Level, hooks ...Hook) Option

WithLevelHooks tells the logger to register and execute hooks at related severity log levels. If VerbosityAll is given, then the given hooks will be registered with each severity log level, including the debug V levels. On the other hand, if VerbosityNone is given, hooks will not be registered with any severity log level.

func WithLogMetrics

func WithLogMetrics() Option

WithLogMetrics tells the logger to collect metrics about log messages.

func WithMaxDepth

func WithMaxDepth(depth int) Option

WithMaxDepth tells the logger how many levels of nested fields (e.g. a struct that contains a struct, etc.) it may log. Every time it finds a struct, slice, array, or map the depth is increased by one. When the maximum is reached, the value will be converted to a string indicating that the max depth has been exceeded. If this field is not specified, a default value will be used.

func WithSink

func WithSink(sink io.Writer) Option

WithSink tells the logger to log to the given sync. The provided sync should be safe for concurrent use, if it is not then it should be wrapped with Lock helper.

func WithTimestamp

func WithTimestamp() Option

WithTimestamp tells the logger to add a "timestamp" key to log lines. This has some overhead, so some users might not want it.

func WithTimestampLayout

func WithTimestampLayout(layout string) Option

WithTimestampLayout tells the logger how to render timestamps when WithTimestamp is enabled. If not specified, a default format will be used. For more details, see docs for Go's time.Layout.

func WithVerbosity

func WithVerbosity(verbosity Level) Option

WithVerbosity tells the logger which verbosity level should be logged by default.

type Options

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

Options specifies parameters that affect logger behavior.

type PseudoStruct

type PseudoStruct []interface{}

PseudoStruct is a list of key-value pairs that gets logged as a struct. E.g.: PseudoStruct{"f1", 1, "f2", true, "f3", []int{}}.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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