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 ¶
- Constants
- func Lock(w io.Writer) io.Writer
- func ModifyDefaults(opts ...Option)
- func RegistryIterate(fn func(id, path string, verbosity Level, v uint) (next bool))
- func SetVerbosity(l Logger, v Level) error
- func SetVerbosityByExp(e string, v Level) error
- type Builder
- type Hook
- type Level
- type Logger
- type Marshaler
- type MessageCategory
- type Option
- func WithCaller(category MessageCategory) Option
- func WithCallerDepth(depth int) Option
- func WithCallerFunc() Option
- func WithJSONOutput() Option
- func WithLevelHooks(l Level, hooks ...Hook) Option
- func WithLogMetrics() Option
- func WithMaxDepth(depth int) Option
- func WithSink(sink io.Writer) Option
- func WithTimestamp() Option
- func WithTimestampLayout(layout string) Option
- func WithVerbosity(verbosity Level) Option
- type Options
- type PseudoStruct
Examples ¶
Constants ¶
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 ¶
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 ¶
RegistryIterate iterates through all registered loggers.
func SetVerbosity ¶
SetVerbosity sets the level of verbosity of the given logger.
func SetVerbosityByExp ¶
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 ¶
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 ParseVerbosityLevel ¶
ParseVerbosityLevel returns a verbosity Level parsed from the given s.
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.
func NewLogger ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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{}}.