Documentation
¶
Overview ¶
Package log provides a high-performance structured logging library.
This package supports two logging styles:
1. Geth-style variadic logging (recommended for compatibility):
log := log.New("component", "myapp")
log.Info("server started", "port", 8080)
log.Debug("processing request", "id", reqID, "user", userID)
2. Method chaining (zero-allocation):
log := log.NewWriter(os.Stderr).With().Str("component", "myapp").Logger()
log.Info().Str("port", "8080").Msg("server started")
Both styles can be mixed. The geth-style methods internally use the zero-allocation Event system for high performance.
Index ¶
- Constants
- Variables
- func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)
- func Crit(msg string, ctx ...interface{})
- func Debug(msg string, ctx ...interface{})
- func DisableSampling(v bool)
- func DiscardHandler() slog.Handler
- func Error(msg string, ctx ...interface{})
- func Fatal(msg string, ctx ...interface{})
- func FormatLogfmtUint64(n uint64) string
- func FormatSlogValue(v slog.Value, tmp []byte) (result []byte)
- func FromLegacyLevel(lvl int) slog.Level
- func Info(msg string, ctx ...interface{})
- func IsInternalPackage(pkg string) bool
- func JSONHandler(wr io.Writer) slog.Handler
- func JSONHandlerWithLevel(wr io.Writer, level slog.Leveler) slog.Handler
- func LevelAlignedString(l slog.Level) string
- func LevelString(l slog.Level) string
- func Log(level Level, msg string, ctx ...interface{})
- func LogfmtHandler(wr io.Writer) slog.Handler
- func LogfmtHandlerWithLevel(wr io.Writer, level slog.Leveler) slog.Handler
- func LvlFromString(lvlString string) (slog.Level, error)
- func RegisterInternalPackages(packages ...string)
- func SetDefault(l Logger)
- func SetGlobalLevel(l Level)
- func SetSlogDefault(l SlogLogger)
- func SyncWriter(w io.Writer) io.Writer
- func Trace(msg string, ctx ...interface{})
- func Warn(msg string, ctx ...interface{})
- func WithContext(ctx context.Context, l Logger) context.Context
- type Array
- func (a *Array) Bool(b bool) *Array
- func (a *Array) Bytes(val []byte) *Array
- func (a *Array) Dict(dict *Event) *Array
- func (a *Array) Dur(d time.Duration) *Array
- func (a *Array) Err(err error) *Array
- func (a *Array) Errs(errs []error) *Array
- func (a *Array) Float32(f float32) *Array
- func (a *Array) Float64(f float64) *Array
- func (a *Array) Hex(val []byte) *Array
- func (a *Array) IPAddr(ip net.IP) *Array
- func (a *Array) IPPrefix(pfx net.IPNet) *Array
- func (a *Array) Int(i int) *Array
- func (a *Array) Int8(i int8) *Array
- func (a *Array) Int16(i int16) *Array
- func (a *Array) Int32(i int32) *Array
- func (a *Array) Int64(i int64) *Array
- func (a *Array) Interface(i interface{}) *Array
- func (a *Array) MACAddr(ha net.HardwareAddr) *Array
- func (*Array) MarshalLogArray(*Array)
- func (a *Array) Object(obj LogObjectMarshaler) *Array
- func (a *Array) RawJSON(val []byte) *Array
- func (a *Array) Str(val string) *Array
- func (a *Array) Time(t time.Time) *Array
- func (a *Array) Type(val interface{}) *Array
- func (a *Array) Uint(i uint) *Array
- func (a *Array) Uint8(i uint8) *Array
- func (a *Array) Uint16(i uint16) *Array
- func (a *Array) Uint32(i uint32) *Array
- func (a *Array) Uint64(i uint64) *Array
- type BasicSampler
- type BurstSampler
- type Color
- type Config
- type ConsoleWriter
- type Context
- func (c Context) AnErr(key string, err error) Context
- func (c Context) Any(key string, i interface{}) Context
- func (c Context) Array(key string, arr LogArrayMarshaler) Context
- func (c Context) Bool(key string, b bool) Context
- func (c Context) Bools(key string, b []bool) Context
- func (c Context) Bytes(key string, val []byte) Context
- func (c Context) Caller() Context
- func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context
- func (c Context) CreateArray() *Array
- func (c Context) CreateDict() *Event
- func (c Context) Ctx(ctx context.Context) Context
- func (c Context) Dict(key string, dict *Event) Context
- func (c Context) Dur(key string, d time.Duration) Context
- func (c Context) Durs(key string, d []time.Duration) Context
- func (c Context) EmbedObject(obj LogObjectMarshaler) Context
- func (c Context) Err(err error) Context
- func (c Context) Errs(key string, errs []error) Context
- func (c Context) Fields(fields interface{}) Context
- func (c Context) Float32(key string, f float32) Context
- func (c Context) Float64(key string, f float64) Context
- func (c Context) Floats32(key string, f []float32) Context
- func (c Context) Floats64(key string, f []float64) Context
- func (c Context) Hex(key string, val []byte) Context
- func (c Context) IPAddr(key string, ip net.IP) Context
- func (c Context) IPAddrs(key string, ip []net.IP) Context
- func (c Context) IPPrefix(key string, pfx net.IPNet) Context
- func (c Context) IPPrefixes(key string, pfx []net.IPNet) Context
- func (c Context) Int(key string, i int) Context
- func (c Context) Int8(key string, i int8) Context
- func (c Context) Int16(key string, i int16) Context
- func (c Context) Int32(key string, i int32) Context
- func (c Context) Int64(key string, i int64) Context
- func (c Context) Interface(key string, i interface{}) Context
- func (c Context) Ints(key string, i []int) Context
- func (c Context) Ints8(key string, i []int8) Context
- func (c Context) Ints16(key string, i []int16) Context
- func (c Context) Ints32(key string, i []int32) Context
- func (c Context) Ints64(key string, i []int64) Context
- func (c Context) Logger() Logger
- func (c Context) MACAddr(key string, ha net.HardwareAddr) Context
- func (c Context) Object(key string, obj LogObjectMarshaler) Context
- func (c Context) Objects(key string, objs []LogObjectMarshaler) Context
- func (c Context) RawJSON(key string, b []byte) Context
- func (c Context) Reset() Context
- func (c Context) Stack() Context
- func (c Context) Str(key, val string) Context
- func (c Context) Stringer(key string, val fmt.Stringer) Context
- func (c Context) Stringers(key string, vals []fmt.Stringer) Context
- func (c Context) Strs(key string, vals []string) Context
- func (c Context) Time(key string, t time.Time) Context
- func (c Context) Times(key string, t []time.Time) Context
- func (c Context) Timestamp() Context
- func (c Context) Type(key string, val interface{}) Context
- func (c Context) Uint(key string, i uint) Context
- func (c Context) Uint8(key string, i uint8) Context
- func (c Context) Uint16(key string, i uint16) Context
- func (c Context) Uint32(key string, i uint32) Context
- func (c Context) Uint64(key string, i uint64) Context
- func (c Context) Uints(key string, i []uint) Context
- func (c Context) Uints8(key string, i []uint8) Context
- func (c Context) Uints16(key string, i []uint16) Context
- func (c Context) Uints32(key string, i []uint32) Context
- func (c Context) Uints64(key string, i []uint64) Context
- type DedupSampler
- type Event
- func (e *Event) AnErr(key string, err error) *Event
- func (e *Event) Any(key string, i interface{}) *Event
- func (e *Event) Array(key string, arr LogArrayMarshaler) *Event
- func (e *Event) Bool(key string, b bool) *Event
- func (e *Event) Bools(key string, b []bool) *Event
- func (e *Event) Bytes(key string, val []byte) *Event
- func (e *Event) Caller(skip ...int) *Event
- func (e *Event) CallerSkipFrame(skip int) *Event
- func (e *Event) CreateArray() *Array
- func (e *Event) CreateDict() *Event
- func (e *Event) Ctx(ctx context.Context) *Event
- func (e *Event) Dict(key string, dict *Event) *Event
- func (e *Event) Discard() *Event
- func (e *Event) Dur(key string, d time.Duration) *Event
- func (e *Event) Durs(key string, d []time.Duration) *Event
- func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event
- func (e *Event) Enabled() bool
- func (e *Event) Err(err error) *Event
- func (e *Event) Errs(key string, errs []error) *Event
- func (e *Event) Fields(fields interface{}) *Event
- func (e *Event) Float32(key string, f float32) *Event
- func (e *Event) Float64(key string, f float64) *Event
- func (e *Event) Floats32(key string, f []float32) *Event
- func (e *Event) Floats64(key string, f []float64) *Event
- func (e *Event) Func(f func(e *Event)) *Event
- func (e *Event) GetCtx() context.Context
- func (e *Event) Hex(key string, val []byte) *Event
- func (e *Event) IPAddr(key string, ip net.IP) *Event
- func (e *Event) IPAddrs(key string, ip []net.IP) *Event
- func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event
- func (e *Event) IPPrefixes(key string, pfx []net.IPNet) *Event
- func (e *Event) Int(key string, i int) *Event
- func (e *Event) Int8(key string, i int8) *Event
- func (e *Event) Int16(key string, i int16) *Event
- func (e *Event) Int32(key string, i int32) *Event
- func (e *Event) Int64(key string, i int64) *Event
- func (e *Event) Interface(key string, i interface{}) *Event
- func (e *Event) Ints(key string, i []int) *Event
- func (e *Event) Ints8(key string, i []int8) *Event
- func (e *Event) Ints16(key string, i []int16) *Event
- func (e *Event) Ints32(key string, i []int32) *Event
- func (e *Event) Ints64(key string, i []int64) *Event
- func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event
- func (e *Event) Msg(msg string)
- func (e *Event) MsgFunc(createMsg func() string)
- func (e *Event) Msgf(format string, v ...interface{})
- func (e *Event) Object(key string, obj LogObjectMarshaler) *Event
- func (e *Event) Objects(key string, objs []LogObjectMarshaler) *Event
- func (e *Event) RawCBOR(key string, b []byte) *Event
- func (e *Event) RawJSON(key string, b []byte) *Event
- func (e *Event) Send()
- func (e *Event) Stack() *Event
- func (e *Event) Str(key, val string) *Event
- func (e *Event) Stringer(key string, val fmt.Stringer) *Event
- func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event
- func (e *Event) Strs(key string, vals []string) *Event
- func (e *Event) Time(key string, t time.Time) *Event
- func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event
- func (e *Event) Times(key string, t []time.Time) *Event
- func (e *Event) Timestamp() *Event
- func (e *Event) Type(key string, val interface{}) *Event
- func (e *Event) Uint(key string, i uint) *Event
- func (e *Event) Uint8(key string, i uint8) *Event
- func (e *Event) Uint16(key string, i uint16) *Event
- func (e *Event) Uint32(key string, i uint32) *Event
- func (e *Event) Uint64(key string, i uint64) *Event
- func (e *Event) Uints(key string, i []uint) *Event
- func (e *Event) Uints8(key string, i []uint8) *Event
- func (e *Event) Uints16(key string, i []uint16) *Event
- func (e *Event) Uints32(key string, i []uint32) *Event
- func (e *Event) Uints64(key string, i []uint64) *Event
- type Factory
- type Field
- func AnErr(key string, err error) Field
- func Any(key string, val interface{}) Field
- func Binary(key string, val []byte) Field
- func Bool(key string, val bool) Field
- func Bools(key string, val []bool) Field
- func ByteString(key string, val []byte) Field
- func Dur(key string, val time.Duration) Field
- func Duration(key string, val time.Duration) Field
- func Durations(key string, val []time.Duration) Field
- func Err(err error) Field
- func Float32(key string, val float32) Field
- func Float64(key string, val float64) Field
- func Float64s(key string, val []float64) Field
- func Int(key string, val int) Field
- func Int8(key string, val int8) Field
- func Int16(key string, val int16) Field
- func Int32(key string, val int32) Field
- func Int64(key string, val int64) Field
- func Int64s(key string, val []int64) Field
- func Ints(key string, val []int) Field
- func NamedErr(key string, err error) Field
- func Reflect(key string, val interface{}) Field
- func Stack(key string) Field
- func Str(key, val string) Field
- func String(key, val string) Field
- func Stringer(key string, val fmt.Stringer) Field
- func Strings(key string, val []string) Field
- func Time(key string, val time.Time) Field
- func Times(key string, val []time.Time) Field
- func Uint(key string, val uint) Field
- func Uint8(key string, val uint8) Field
- func Uint16(key string, val uint16) Field
- func Uint32(key string, val uint32) Field
- func Uint64(key string, val uint64) Field
- func Uint64s(key string, val []uint64) Field
- func UserString(key, val string) Field
- type FilteredLevelWriter
- type Formatter
- type FormatterByFieldName
- type GlogHandler
- func (h *GlogHandler) Enabled(ctx context.Context, level slog.Level) bool
- func (h *GlogHandler) Handle(ctx context.Context, r slog.Record) error
- func (h *GlogHandler) Verbosity(level slog.Level)
- func (h *GlogHandler) Vmodule(pattern string) error
- func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *GlogHandler) WithGroup(name string) slog.Handler
- type Hook
- type HookFunc
- type Level
- type LevelHook
- type LevelSampler
- type LevelWriter
- type LevelWriterAdapter
- type LogArrayMarshaler
- type LogFormat
- type LogObjectMarshaler
- type Logger
- func Ctx(ctx context.Context) Logger
- func Default() Logger
- func InitLogger(chainAlias string, logLevel string, jsonFormat bool, writer io.Writer) (Logger, error)
- func New(ctx ...interface{}) Logger
- func NewNoOpLogger() Logger
- func NewTestLogger(level ...Level) Logger
- func NewWriter(w io.Writer) Logger
- func Noop() Logger
- func Root() Logger
- type NoLog
- func (NoLog) Crit(string, ...interface{})
- func (NoLog) Debug(string, ...interface{})
- func (NoLog) DebugEvent() *Event
- func (NoLog) Enabled(context.Context, slog.Level) bool
- func (NoLog) Err(error) *Event
- func (NoLog) Error(string, ...interface{})
- func (NoLog) ErrorEvent() *Event
- func (NoLog) Fatal(string, ...interface{})
- func (NoLog) FatalEvent() *Event
- func (NoLog) GetLevel() Level
- func (NoLog) Hook(...Hook) Logger
- func (NoLog) Info(string, ...interface{})
- func (NoLog) InfoEvent() *Event
- func (NoLog) IsZero() bool
- func (NoLog) Level(Level) Logger
- func (NoLog) Log(Level, string, ...interface{})
- func (NoLog) LogEvent() *Event
- func (NoLog) New(...interface{}) Logger
- func (NoLog) Output(io.Writer) Logger
- func (NoLog) Panic(string, ...interface{})
- func (NoLog) PanicEvent() *Event
- func (NoLog) Print(...interface{})
- func (NoLog) Printf(string, ...interface{})
- func (NoLog) RecoverAndPanic(fn func())
- func (NoLog) Sample(Sampler) Logger
- func (NoLog) SetLogLevel(string) error
- func (NoLog) Trace(string, ...interface{})
- func (NoLog) TraceEvent() *Event
- func (NoLog) Verbo(string, ...interface{})
- func (NoLog) Warn(string, ...interface{})
- func (NoLog) WarnEvent() *Event
- func (NoLog) With() Context
- func (NoLog) WithLevel(Level) *Event
- func (NoLog) Write(p []byte) (int, error)
- type RandomSampler
- type RotatingWriterConfig
- type Sampler
- type SlogLogger
- type TerminalHandler
- func (h *TerminalHandler) Enabled(_ context.Context, level slog.Level) bool
- func (h *TerminalHandler) Handle(_ context.Context, r slog.Record) error
- func (h *TerminalHandler) ResetFieldPadding()
- func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *TerminalHandler) WithGroup(name string) slog.Handler
- type TerminalStringer
- type TestWriter
- type TestingLog
- type TriggerLevelWriter
Constants ¶
const ( // TimeFormatUnix defines a time format that makes time fields to be // serialized as Unix timestamp integers. TimeFormatUnix = "" // TimeFormatUnixMs defines a time format that makes time fields to be // serialized as Unix timestamp integers in milliseconds. TimeFormatUnixMs = "UNIXMS" // TimeFormatUnixMicro defines a time format that makes time fields to be // serialized as Unix timestamp integers in microseconds. TimeFormatUnixMicro = "UNIXMICRO" // TimeFormatUnixNano defines a time format that makes time fields to be // serialized as Unix timestamp integers in nanoseconds. TimeFormatUnixNano = "UNIXNANO" // DurationFormatFloat defines a format for Duration fields that makes duration fields to be // serialized as floating point numbers. DurationFormatFloat = "float" // DurationFormatInt defines a format for Duration fields that makes duration fields to be // serialized as integers. DurationFormatInt = "int" // DurationFormatString defines a format for Duration fields that makes duration fields to be // serialized as string. DurationFormatString = "string" )
const ( // Exported slog.Level constants for use with Logger.Enabled() SlogLevelTrace slog.Level = slogLevelTrace SlogLevelDebug = slogLevelDebug SlogLevelInfo = slogLevelInfo SlogLevelWarn = slogLevelWarn SlogLevelError = slogLevelError SlogLevelCrit = slogLevelCrit )
slog.Level constants for slog-based handlers
Variables ¶
var ( // TimestampFieldName is the field name used for the timestamp field. TimestampFieldName = "time" // LevelFieldName is the field name used for the level field. LevelFieldName = "level" // LevelTraceValue is the value used for the trace level field. LevelTraceValue = "trace" // LevelDebugValue is the value used for the debug level field. LevelDebugValue = "debug" // LevelInfoValue is the value used for the info level field. LevelInfoValue = "info" // LevelWarnValue is the value used for the warn level field. LevelWarnValue = "warn" // LevelErrorValue is the value used for the error level field. LevelErrorValue = "error" // LevelFatalValue is the value used for the fatal level field. LevelFatalValue = "fatal" // LevelPanicValue is the value used for the panic level field. LevelPanicValue = "panic" // LevelFieldMarshalFunc allows customization of global level field marshaling. LevelFieldMarshalFunc = func(l Level) string { return l.String() } // MessageFieldName is the field name used for the message field. MessageFieldName = "message" // ErrorFieldName is the field name used for error fields. ErrorFieldName = "error" // CallerFieldName is the field name used for caller field. CallerFieldName = "caller" // CallerSkipFrameCount is the number of stack frames to skip to find the caller. CallerSkipFrameCount = 2 // CallerMarshalFunc allows customization of global caller marshaling CallerMarshalFunc = func(pc uintptr, file string, line int) string { return file + ":" + strconv.Itoa(line) } // ErrorStackFieldName is the field name used for error stacks. ErrorStackFieldName = "stack" // ErrorStackMarshaler extract the stack from err if any. ErrorStackMarshaler func(err error) interface{} // ErrorMarshalFunc allows customization of global error marshaling ErrorMarshalFunc = func(err error) interface{} { return err } // InterfaceMarshalFunc allows customization of interface marshaling. // Default: "encoding/json.Marshal" with disabled HTML escaping InterfaceMarshalFunc = func(v interface{}) ([]byte, error) { var buf bytes.Buffer encoder := json.NewEncoder(&buf) encoder.SetEscapeHTML(false) err := encoder.Encode(v) if err != nil { return nil, err } b := buf.Bytes() if len(b) > 0 { return b[:len(b)-1], nil } return b, nil } // TimeFieldFormat defines the time format of the Time field type. If set to // TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX // timestamp as integer. TimeFieldFormat = time.RFC3339 // TimestampFunc defines the function called to generate a timestamp. TimestampFunc = time.Now // DurationFieldFormat defines the format of the Duration field type. DurationFieldFormat = DurationFormatFloat // DurationFieldUnit defines the unit for time.Duration type fields added // using the Dur method. DurationFieldUnit = time.Millisecond // DurationFieldInteger renders Dur fields as integer instead of float if // set to true. // Deprecated: use DurationFieldFormat with DurationFormatInt instead. DurationFieldInteger = false // ErrorHandler is called whenever logger fails to write an event on its // output. If not set, an error is printed on the stderr. This handler must // be thread safe and non-blocking. ErrorHandler func(err error) // DefaultContextLogger is returned from Ctx() if there is no logger associated // with the context. DefaultContextLogger Logger // LevelColors are used by ConsoleWriter's consoleDefaultFormatLevel to color // log levels. LevelColors = map[Level]int{ TraceLevel: colorBlue, DebugLevel: colorMagenta, InfoLevel: colorGreen, WarnLevel: colorYellow, ErrorLevel: colorRed, FatalLevel: colorRed, PanicLevel: colorRed, } // FormattedLevels are used by ConsoleWriter's consoleDefaultFormatLevel // for a short level name. FormattedLevels = map[Level]string{ TraceLevel: "trace", DebugLevel: "debug", InfoLevel: "info", WarnLevel: "warn", ErrorLevel: "error", FatalLevel: "fatal", PanicLevel: "panic", } // TriggerLevelWriterBufferReuseLimit is a limit in bytes that a buffer is dropped // from the TriggerLevelWriter buffer pool if the buffer grows above the limit. TriggerLevelWriterBufferReuseLimit = 64 * 1024 // FloatingPointPrecision, if set to a value other than -1, controls the number // of digits when formatting float numbers in JSON. See strconv.FormatFloat for // more details. FloatingPointPrecision = -1 )
var ( // Often samples log every ~ 10 events. Often = RandomSampler(10) // Sometimes samples log every ~ 100 events. Sometimes = RandomSampler(100) // Rarely samples log every ~ 1000 events. Rarely = RandomSampler(1000) )
var ErrUnknownLevel = errors.New("unknown log level")
ErrUnknownLevel is returned when parsing an unknown log level string.
Functions ¶
func ConsoleTestWriter ¶ added in v1.4.2
func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)
ConsoleTestWriter creates an option that correctly sets the file frame depth for testing.TB log.
func Crit ¶
func Crit(msg string, ctx ...interface{})
Crit is an alias for Fatal (geth compatibility)
func Debug ¶
func Debug(msg string, ctx ...interface{})
Debug logs at debug level with geth-style context
func DisableSampling ¶ added in v1.4.2
func DisableSampling(v bool)
DisableSampling will disable sampling in all Loggers if true.
func Error ¶
func Error(msg string, ctx ...interface{})
Error logs at error level with geth-style context
func Fatal ¶ added in v1.4.2
func Fatal(msg string, ctx ...interface{})
Fatal logs at fatal level with geth-style context and exits
func FormatLogfmtUint64 ¶
FormatLogfmtUint64 formats a uint64 as a compact logfmt string.
func FormatSlogValue ¶
FormatSlogValue formats a slog.Value for serialization to terminal.
func FromLegacyLevel ¶
FromLegacyLevel converts old geth verbosity level to slog.Level.
func Info ¶
func Info(msg string, ctx ...interface{})
Info logs at info level with geth-style context
func IsInternalPackage ¶ added in v1.4.2
func JSONHandler ¶
JSONHandler returns a handler which prints records in JSON format.
func JSONHandlerWithLevel ¶
JSONHandlerWithLevel returns a JSON handler with level filtering.
func LevelAlignedString ¶
LevelAlignedString returns a 5-character string containing the name of a level.
func LevelString ¶
LevelString returns a string containing the name of a level.
func LogfmtHandler ¶
LogfmtHandler returns a handler which prints records in logfmt format.
func LogfmtHandlerWithLevel ¶
LogfmtHandlerWithLevel returns a logfmt handler with level filtering.
func LvlFromString ¶ added in v1.4.2
LvlFromString returns the appropriate level from a string name.
func RegisterInternalPackages ¶ added in v1.0.4
func RegisterInternalPackages(packages ...string)
func SetDefault ¶
func SetDefault(l Logger)
SetDefault sets the default logger for geth-style functions
func SetGlobalLevel ¶ added in v1.4.2
func SetGlobalLevel(l Level)
SetGlobalLevel sets the global override for log level. If this values is raised, all Loggers will use at least this value.
To globally disable logs, set GlobalLevel to Disabled.
func SetSlogDefault ¶ added in v1.4.2
func SetSlogDefault(l SlogLogger)
SetSlogDefault sets the default slog-based logger.
func SyncWriter ¶ added in v1.4.2
SyncWriter wraps w so that each call to Write is synchronized with a mutex. This syncer can be used to wrap the call to writer's Write method if it is not thread safe. Note that you do not need this wrapper for os.File Write operations on POSIX and Windows systems as they are already thread-safe.
func Trace ¶
func Trace(msg string, ctx ...interface{})
Trace logs at trace level with geth-style context
func Warn ¶
func Warn(msg string, ctx ...interface{})
Warn logs at warn level with geth-style context
func WithContext ¶ added in v1.4.2
WithContext returns a copy of ctx with the logger attached. The Logger attached to the provided Context (if any) will not be affected.
Note: to modify the existing Logger attached to a Context (instead of replacing it in a new Context), use UpdateContext with the following notation:
ctx := r.Context()
l := logger.Ctx(ctx)
l.UpdateContext(func(c Context) Context {
return c.Str("bar", "baz")
})
Types ¶
type Array ¶ added in v0.1.2
type Array struct {
// contains filtered or unexported fields
}
Array is used to prepopulate an array of items which can be re-used to add to log messages.
func Arr ¶ added in v1.4.2
func Arr() *Array
Arr creates an array to be added to an Event or Context. WARNING: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateArray or Context.CreateArray instead.
func (*Array) IPPrefix ¶ added in v1.4.2
IPPrefix adds a net.IPNet IPv4 or IPv6 Prefix (IP + mask) to the array
func (*Array) MACAddr ¶ added in v1.4.2
func (a *Array) MACAddr(ha net.HardwareAddr) *Array
MACAddr adds a net.HardwareAddr MAC (Ethernet) address to the array
func (*Array) MarshalLogArray ¶ added in v1.4.2
MarshalLogArray method here is no-op - since data is already in the needed format.
func (*Array) Object ¶ added in v1.4.2
func (a *Array) Object(obj LogObjectMarshaler) *Array
Object marshals an object that implement the LogObjectMarshaler interface and appends it to the array.
func (*Array) Time ¶ added in v1.4.2
Time appends t formatted as string using logger.TimeFieldFormat.
type BasicSampler ¶ added in v1.4.2
type BasicSampler struct {
N uint32
// contains filtered or unexported fields
}
BasicSampler is a sampler that will send every Nth events, regardless of their level.
func (*BasicSampler) Sample ¶ added in v1.4.2
func (s *BasicSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type BurstSampler ¶ added in v1.4.2
type BurstSampler struct {
// Burst is the maximum number of event per period allowed before calling
// NextSampler.
Burst uint32
// Period defines the burst period. If 0, NextSampler is always called.
Period time.Duration
// NextSampler is the sampler used after the burst is reached. If nil,
// events are always rejected after the burst.
NextSampler Sampler
// contains filtered or unexported fields
}
BurstSampler lets Burst events pass per Period then pass the decision to NextSampler. If Sampler is not set, all subsequent events are rejected.
func (*BurstSampler) Sample ¶ added in v1.4.2
func (s *BurstSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type Color ¶ added in v0.1.1
type Color int
Color represents an ANSI color code for terminal output
const ( Reset Color = 0 Bold Color = 1 Black Color = 30 Red Color = 31 Green Color = 32 Yellow Color = 33 Blue Color = 34 Purple Color = 35 Cyan Color = 36 LightGray Color = 37 DarkGray Color = 90 LightRed Color = 91 LightGreen Color = 92 LightYellow Color = 93 LightBlue Color = 94 LightPurple Color = 95 LightCyan Color = 96 White Color = 97 Orange Color = 208 // 256-color mode orange )
Color constants for terminal output
type Config ¶ added in v0.1.1
type Config struct {
RotatingWriterConfig
LogLevel Level
DisplayLevel Level
LogFormat LogFormat
DisableWriterDisplaying bool
}
Config represents the logging configuration.
type ConsoleWriter ¶ added in v1.4.2
type ConsoleWriter struct {
// Out is the output destination.
Out io.Writer
// NoColor disables the colorized output.
NoColor bool
// TimeFormat specifies the format for timestamp in output.
TimeFormat string
// TimeLocation tells ConsoleWriter’s default FormatTimestamp
// how to localize the time.
TimeLocation *time.Location
// PartsOrder defines the order of parts in output.
PartsOrder []string
// PartsExclude defines parts to not display in output.
PartsExclude []string
// FieldsOrder defines the order of contextual fields in output.
FieldsOrder []string
// FieldsExclude defines contextual fields to not display in output.
FieldsExclude []string
FormatTimestamp Formatter
FormatLevel Formatter
FormatCaller Formatter
FormatMessage Formatter
FormatFieldName Formatter
FormatFieldValue Formatter
FormatErrFieldName Formatter
FormatErrFieldValue Formatter
// If this is configured it is used for "part" values and
// has precedence on FormatFieldValue
FormatPartValueByName FormatterByFieldName
FormatExtra func(map[string]interface{}, *bytes.Buffer) error
FormatPrepare func(map[string]interface{}) error
// contains filtered or unexported fields
}
ConsoleWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Out.
func NewConsoleWriter ¶ added in v1.4.2
func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter
NewConsoleWriter creates and initializes a new ConsoleWriter.
func (ConsoleWriter) Close ¶ added in v1.4.2
func (w ConsoleWriter) Close() error
Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.
type Context ¶ added in v1.4.2
type Context struct {
// contains filtered or unexported fields
}
Context configures a new sub-logger with contextual fields.
func (Context) AnErr ¶ added in v1.4.2
AnErr adds the field key with serialized err to the logger context. If err is nil, no field is added.
func (Context) Array ¶ added in v1.4.2
func (c Context) Array(key string, arr LogArrayMarshaler) Context
Array adds the field key with an array to the event context. Use c.CreateArray() to create the array or pass a type that implement the LogArrayMarshaler interface.
func (Context) Bool ¶ added in v1.4.2
Bool adds the field key with val as a bool to the logger context.
func (Context) Bools ¶ added in v1.4.2
Bools adds the field key with val as a []bool to the logger context.
func (Context) Bytes ¶ added in v1.4.2
Bytes adds the field key with val as a []byte to the logger context.
func (Context) Caller ¶ added in v1.4.2
Caller adds the file:line of the caller with the logger.CallerFieldName key.
func (Context) CallerWithSkipFrameCount ¶ added in v1.4.2
CallerWithSkipFrameCount adds the file:line of the caller with the logger.CallerFieldName key. The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. If set to -1 the global CallerSkipFrameCount will be used.
func (Context) CreateArray ¶ added in v1.4.2
CreateArray creates an Array to be used with the Context.Array method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the Context.Array method.
func (Context) CreateDict ¶ added in v1.4.2
CreateDict creates an Event to be used with the Context.Dict method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the Context.Dict method.
func (Context) Ctx ¶ added in v1.4.2
Ctx adds the context.Context to the logger context. The context.Context is not rendered in the error message, but is made available for hooks to use. A typical use case is to extract tracing information from the context.Context.
func (Context) Dur ¶ added in v1.4.2
Dur adds the field key with d divided by unit and stored as a float.
func (Context) Durs ¶ added in v1.4.2
Durs adds the field key with d divided by unit and stored as a float.
func (Context) EmbedObject ¶ added in v1.4.2
func (c Context) EmbedObject(obj LogObjectMarshaler) Context
EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.
func (Context) Err ¶ added in v1.4.2
Err adds the field "error" with serialized err to the logger context.
func (Context) Errs ¶ added in v1.4.2
Errs adds the field key with errs as an array of serialized errors to the logger context.
func (Context) Fields ¶ added in v1.4.2
Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.
func (Context) Float32 ¶ added in v1.4.2
Float32 adds the field key with f as a float32 to the logger context.
func (Context) Float64 ¶ added in v1.4.2
Float64 adds the field key with f as a float64 to the logger context.
func (Context) Floats32 ¶ added in v1.4.2
Floats32 adds the field key with f as a []float32 to the logger context.
func (Context) Floats64 ¶ added in v1.4.2
Floats64 adds the field key with f as a []float64 to the logger context.
func (Context) Hex ¶ added in v1.4.2
Hex adds the field key with val as a hex string to the logger context.
func (Context) IPAddr ¶ added in v1.4.2
IPAddr adds adds the field key with ip as a net.IP IPv4 or IPv6 Address to the context
func (Context) IPAddrs ¶ added in v1.4.2
IPAddrs adds the field key with ip as a []net.IP array of IPv4 or IPv6 Address to the context
func (Context) IPPrefix ¶ added in v1.4.2
IPPrefix adds adds the field key with pfx as a []net.IPNet IPv4 or IPv6 Prefix (address and mask) to the context
func (Context) IPPrefixes ¶ added in v1.4.2
IPPrefix adds adds the field key with pfx as a []net.IPNet array of IPv4 or IPv6 Prefix (address and mask) to the context
func (Context) Int8 ¶ added in v1.4.2
Int8 adds the field key with i as a int8 to the logger context.
func (Context) Int16 ¶ added in v1.4.2
Int16 adds the field key with i as a int16 to the logger context.
func (Context) Int32 ¶ added in v1.4.2
Int32 adds the field key with i as a int32 to the logger context.
func (Context) Int64 ¶ added in v1.4.2
Int64 adds the field key with i as a int64 to the logger context.
func (Context) Interface ¶ added in v1.4.2
Interface adds the field key with obj marshaled using reflection.
func (Context) Ints ¶ added in v1.4.2
Ints adds the field key with i as a []int to the logger context.
func (Context) Ints8 ¶ added in v1.4.2
Ints8 adds the field key with i as a []int8 to the logger context.
func (Context) Ints16 ¶ added in v1.4.2
Ints16 adds the field key with i as a []int16 to the logger context.
func (Context) Ints32 ¶ added in v1.4.2
Ints32 adds the field key with i as a []int32 to the logger context.
func (Context) Ints64 ¶ added in v1.4.2
Ints64 adds the field key with i as a []int64 to the logger context.
func (Context) MACAddr ¶ added in v1.4.2
func (c Context) MACAddr(key string, ha net.HardwareAddr) Context
MACAddr adds adds the field key with ha as a net.HardwareAddr MAC address to the context
func (Context) Object ¶ added in v1.4.2
func (c Context) Object(key string, obj LogObjectMarshaler) Context
Object marshals an object that implement the LogObjectMarshaler interface.
func (Context) Objects ¶ added in v1.4.2
func (c Context) Objects(key string, objs []LogObjectMarshaler) Context
Object marshals an object that implement the LogObjectMarshaler interface.
func (Context) RawJSON ¶ added in v1.4.2
RawJSON adds already encoded JSON to context.
No sanity check is performed on b; it must not contain carriage returns and be valid JSON.
func (Context) Stack ¶ added in v1.4.2
Stack enables stack trace printing for the error passed to Err().
func (Context) Str ¶ added in v1.4.2
Str adds the field key with val as a string to the logger context.
func (Context) Stringer ¶ added in v1.4.2
Stringer adds the field key with val.String() (or null if val is nil) to the logger context.
func (Context) Stringers ¶ added in v1.4.2
Stringers adds the field key with vals as an array of strings by calling .String() on each entry to the logger context.
func (Context) Strs ¶ added in v1.4.2
Strs adds the field key with val as a string to the logger context.
func (Context) Time ¶ added in v1.4.2
Time adds the field key with t formatted as string using logger.TimeFieldFormat.
func (Context) Times ¶ added in v1.4.2
Times adds the field key with t formatted as string using logger.TimeFieldFormat.
func (Context) Timestamp ¶ added in v1.4.2
Timestamp adds the current local time to the logger context with the "time" key, formatted using logger.TimeFieldFormat. To customize the key name, change logger.TimestampFieldName. To customize the time format, change logger.TimeFieldFormat.
NOTE: It won't dedupe the "time" key if the *Context has one already.
func (Context) Uint ¶ added in v1.4.2
Uint adds the field key with i as a uint to the logger context.
func (Context) Uint8 ¶ added in v1.4.2
Uint8 adds the field key with i as a uint8 to the logger context.
func (Context) Uint16 ¶ added in v1.4.2
Uint16 adds the field key with i as a uint16 to the logger context.
func (Context) Uint32 ¶ added in v1.4.2
Uint32 adds the field key with i as a uint32 to the logger context.
func (Context) Uint64 ¶ added in v1.4.2
Uint64 adds the field key with i as a uint64 to the logger context.
func (Context) Uints ¶ added in v1.4.2
Uints adds the field key with i as a []uint to the logger context.
func (Context) Uints8 ¶ added in v1.4.2
Uints8 adds the field key with i as a []uint8 to the logger context.
func (Context) Uints16 ¶ added in v1.4.2
Uints16 adds the field key with i as a []uint16 to the logger context.
type DedupSampler ¶ added in v1.4.2
type DedupSampler struct {
// Window is the deduplication time window. Defaults to 1 minute.
Window time.Duration
// MaxKeys is the maximum number of unique messages to track. Defaults to 1000.
MaxKeys int
// contains filtered or unexported fields
}
DedupSampler suppresses duplicate log messages within a time window. After the window expires, it emits a summary of suppressed messages.
func NewDedupSampler ¶ added in v1.4.2
func NewDedupSampler(window time.Duration) *DedupSampler
NewDedupSampler creates a dedup sampler with the given window.
func (*DedupSampler) GetSuppressedCount ¶ added in v1.4.2
func (s *DedupSampler) GetSuppressedCount(lvl Level, msg string) int64
GetSuppressedCount returns the count of suppressed messages for a key.
func (*DedupSampler) Sample ¶ added in v1.4.2
func (s *DedupSampler) Sample(lvl Level) bool
Sample implements the Sampler interface (always returns true for non-dedup use).
func (*DedupSampler) SampleMsg ¶ added in v1.4.2
func (s *DedupSampler) SampleMsg(lvl Level, msg string) bool
SampleMsg returns true if this message should be logged. It tracks message hashes and suppresses duplicates within the window.
func (*DedupSampler) SampleMsgWithKey ¶ added in v1.4.2
func (s *DedupSampler) SampleMsgWithKey(lvl Level, msg, key string) bool
SampleMsgWithKey allows specifying a custom dedup key instead of using msg.
type Event ¶ added in v1.4.2
type Event struct {
// contains filtered or unexported fields
}
Event represents a log event. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.
func Dict ¶ added in v1.4.2
func Dict() *Event
Dict creates an Event to be used with the *Event.Dict method. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method. NOTE: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateDict instead.
func (*Event) AnErr ¶ added in v1.4.2
AnErr adds the field key with serialized err to the *Event context. If err is nil, no field is added.
func (*Event) Array ¶ added in v1.4.2
func (e *Event) Array(key string, arr LogArrayMarshaler) *Event
Array adds the field key with an array to the event context. Use e.CreateArray() to create the array or pass a type that implement the LogArrayMarshaler interface.
func (*Event) Bool ¶ added in v1.4.2
Bool adds the field key with val as a bool to the *Event context.
func (*Event) Bools ¶ added in v1.4.2
Bools adds the field key with val as a []bool to the *Event context.
func (*Event) Bytes ¶ added in v1.4.2
Bytes adds the field key with val as a string to the *Event context.
Runes outside of normal ASCII ranges will be hex-encoded in the resulting JSON.
func (*Event) Caller ¶ added in v1.4.2
Caller adds the file:line of the caller with the logger.CallerFieldName key. The argument skip is the number of stack frames to ascend Skip If not passed, use the global variable CallerSkipFrameCount
func (*Event) CallerSkipFrame ¶ added in v1.4.2
CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. This includes those added via hooks from the context.
func (*Event) CreateArray ¶ added in v1.4.2
CreateArray creates an Array to be used with the *Event.Array method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the *Event.Array method.
func (*Event) CreateDict ¶ added in v1.4.2
CreateDict creates an Event to be used with the *Event.Dict method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.
func (*Event) Ctx ¶ added in v1.4.2
Ctx adds the Go Context to the *Event context. The context is not rendered in the output message, but is available to hooks and to Func() calls via the GetCtx() accessor. A typical use case is to extract tracing information from the Go Ctx.
func (*Event) Dict ¶ added in v1.4.2
Dict adds the field key with a dict to the event context. Use e.CreateDict() to create the dictionary.
func (*Event) Dur ¶ added in v1.4.2
Dur adds the field key with duration d stored as logger.DurationFieldUnit. If logger.DurationFieldInteger is true, durations are rendered as integer instead of float.
func (*Event) Durs ¶ added in v1.4.2
Durs adds the field key with duration d stored as logger.DurationFieldUnit. If logger.DurationFieldInteger is true, durations are rendered as integer instead of float.
func (*Event) EmbedObject ¶ added in v1.4.2
func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event
EmbedObject marshals an object that implement the LogObjectMarshaler interface.
func (*Event) Enabled ¶ added in v1.4.2
Enabled return false if the *Event is going to be filtered out by log level or sampling.
func (*Event) Err ¶ added in v1.4.2
Err adds the field "error" with serialized err to the *Event context. If err is nil, no field is added.
To customize the key name, change logger.ErrorFieldName.
If Stack() has been called before and logger.ErrorStackMarshaler is defined, the err is passed to ErrorStackMarshaler and the result is appended to the logger.ErrorStackFieldName.
func (*Event) Errs ¶ added in v1.4.2
Errs adds the field key with errs as an array of serialized errors to the *Event context.
func (*Event) Fields ¶ added in v1.4.2
Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.
func (*Event) Float32 ¶ added in v1.4.2
Float32 adds the field key with f as a float32 to the *Event context.
func (*Event) Float64 ¶ added in v1.4.2
Float64 adds the field key with f as a float64 to the *Event context.
func (*Event) Floats32 ¶ added in v1.4.2
Floats32 adds the field key with f as a []float32 to the *Event context.
func (*Event) Floats64 ¶ added in v1.4.2
Floats64 adds the field key with f as a []float64 to the *Event context.
func (*Event) Func ¶ added in v1.4.2
Func allows an anonymous func to run only if the event is enabled.
func (*Event) GetCtx ¶ added in v1.4.2
GetCtx retrieves the Go context.Context which is optionally stored in the Event. This allows Hooks and functions passed to Func() to retrieve values which are stored in the context.Context. This can be useful in tracing, where span information is commonly propagated in the context.Context.
func (*Event) Hex ¶ added in v1.4.2
Hex adds the field key with val as a hex string to the *Event context.
func (*Event) IPAddr ¶ added in v1.4.2
IPAddr adds the field key with ip as a net.IP IPv4 or IPv6 Address to the event
func (*Event) IPAddrs ¶ added in v1.4.2
IPAddrs adds the field key with ip as a net.IP array of IPv4 or IPv6 Address to the event
func (*Event) IPPrefix ¶ added in v1.4.2
IPPrefix adds the field key with pfx as a net.IPNet IPv4 or IPv6 Prefix (address and mask) to the event
func (*Event) IPPrefixes ¶ added in v1.4.2
IPPrefixes the field key with pfx as a net.IPNet array of IPv4 or IPv6 Prefixes (address and mask) to the event
func (*Event) Int8 ¶ added in v1.4.2
Int8 adds the field key with i as a int8 to the *Event context.
func (*Event) Int16 ¶ added in v1.4.2
Int16 adds the field key with i as a int16 to the *Event context.
func (*Event) Int32 ¶ added in v1.4.2
Int32 adds the field key with i as a int32 to the *Event context.
func (*Event) Int64 ¶ added in v1.4.2
Int64 adds the field key with i as a int64 to the *Event context.
func (*Event) Interface ¶ added in v1.4.2
Interface adds the field key with i marshaled using reflection.
func (*Event) Ints ¶ added in v1.4.2
Ints adds the field key with i as a []int to the *Event context.
func (*Event) Ints8 ¶ added in v1.4.2
Ints8 adds the field key with i as a []int8 to the *Event context.
func (*Event) Ints16 ¶ added in v1.4.2
Ints16 adds the field key with i as a []int16 to the *Event context.
func (*Event) Ints32 ¶ added in v1.4.2
Ints32 adds the field key with i as a []int32 to the *Event context.
func (*Event) Ints64 ¶ added in v1.4.2
Ints64 adds the field key with i as a []int64 to the *Event context.
func (*Event) MACAddr ¶ added in v1.4.2
func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event
MACAddr the field key with ha as a net.HardwareAddr MAC address to the event
func (*Event) Msg ¶ added in v1.4.2
Msg sends the *Event with msg added as the message field if not empty.
NOTICE: once this method is called, the *Event should be disposed. Calling Msg twice can have unexpected result.
func (*Event) Msgf ¶ added in v1.4.2
Msgf sends the event with formatted msg added as the message field if not empty.
NOTICE: once this method is called, the *Event should be disposed. Calling Msgf twice can have unexpected result.
func (*Event) Object ¶ added in v1.4.2
func (e *Event) Object(key string, obj LogObjectMarshaler) *Event
Object marshals an object that implement the LogObjectMarshaler interface.
func (*Event) Objects ¶ added in v1.4.2
func (e *Event) Objects(key string, objs []LogObjectMarshaler) *Event
Objects adds the field key with obj as an array of objects that implement the LogObjectMarshaler interface.
func (*Event) RawCBOR ¶ added in v1.4.2
RawCBOR adds already encoded CBOR to the log line under key.
No sanity check is performed on b Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url
func (*Event) RawJSON ¶ added in v1.4.2
RawJSON adds already encoded JSON to the log line under key.
No sanity check is performed on b; it must not contain carriage returns and be valid JSON.
func (*Event) Send ¶ added in v1.4.2
func (e *Event) Send()
Send is equivalent to calling Msg("").
NOTICE: once this method is called, the *Event should be disposed.
func (*Event) Stack ¶ added in v1.4.2
Stack enables stack trace printing for the error passed to Err().
ErrorStackMarshaler must be set for this method to do something.
func (*Event) Str ¶ added in v1.4.2
Str adds the field key with val as a string to the *Event context.
func (*Event) Stringer ¶ added in v1.4.2
Stringer adds the field key with val.String() (or null if val is nil) to the *Event context.
func (*Event) Stringers ¶ added in v1.4.2
Stringers adds the field key with vals where each individual val is used as val.String() (or null if val is empty) to the *Event context.
func (*Event) Strs ¶ added in v1.4.2
Strs adds the field key with vals as a []string to the *Event context.
func (*Event) Time ¶ added in v1.4.2
Time adds the field key with t formatted as string using logger.TimeFieldFormat.
func (*Event) TimeDiff ¶ added in v1.4.2
TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().
func (*Event) Times ¶ added in v1.4.2
Times adds the field key with t formatted as string using logger.TimeFieldFormat.
func (*Event) Timestamp ¶ added in v1.4.2
Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key. To customize the key name, change logger.TimestampFieldName.
NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one already.
func (*Event) Uint ¶ added in v1.4.2
Uint adds the field key with i as a uint to the *Event context.
func (*Event) Uint8 ¶ added in v1.4.2
Uint8 adds the field key with i as a uint8 to the *Event context.
func (*Event) Uint16 ¶ added in v1.4.2
Uint16 adds the field key with i as a uint16 to the *Event context.
func (*Event) Uint32 ¶ added in v1.4.2
Uint32 adds the field key with i as a uint32 to the *Event context.
func (*Event) Uint64 ¶ added in v1.4.2
Uint64 adds the field key with i as a uint64 to the *Event context.
func (*Event) Uints ¶ added in v1.4.2
Uints adds the field key with i as a []int to the *Event context.
func (*Event) Uints8 ¶ added in v1.4.2
Uints8 adds the field key with i as a []int8 to the *Event context.
func (*Event) Uints16 ¶ added in v1.4.2
Uints16 adds the field key with i as a []int16 to the *Event context.
type Factory ¶
type Factory interface {
// Make creates a new logger with the given name.
Make(name string) (Logger, error)
// MakeChain creates a logger for a blockchain with the given alias.
MakeChain(alias string) (Logger, error)
// MakeChainAndIndex creates loggers for a blockchain and its indexer.
MakeChainAndIndex(alias string, index string) (Logger, Logger, error)
// SetLogLevel sets the log level for a named logger.
SetLogLevel(name string, level Level)
// SetDisplayLevel sets the display level for a named logger.
SetDisplayLevel(name string, level Level)
// GetLogLevel returns the log level for a named logger.
GetLogLevel(name string) (Level, error)
// GetDisplayLevel returns the display level for a named logger.
GetDisplayLevel(name string) (Level, error)
// Close closes all log files.
Close()
}
Factory creates loggers with shared configuration.
func NewFactory ¶
func NewFactory() Factory
NewFactory creates a new logger factory with default configuration.
func NewFactoryWithConfig ¶ added in v0.1.1
NewFactoryWithConfig creates a new logger factory with the given configuration.
type Field ¶
type Field struct {
Key string
Value interface{}
}
Field represents a key-value pair for geth-style structured logging. This provides compatibility with go-ethereum's logging patterns.
func ByteString ¶ added in v0.1.2
func UserString ¶ added in v0.1.1
UserString returns a Field for user-provided string values. This is the same as String but semantically indicates user input.
type FilteredLevelWriter ¶ added in v1.4.2
type FilteredLevelWriter struct {
Writer LevelWriter
Level Level
}
FilteredLevelWriter writes only logs at Level or above to Writer.
It should be used only in combination with MultiLevelWriter when you want to write to multiple destinations at different levels. Otherwise you should just set the level on the logger and filter events early. When using MultiLevelWriter then you set the level on the logger to the lowest of the levels you use for writers.
func (*FilteredLevelWriter) Close ¶ added in v1.4.2
func (w *FilteredLevelWriter) Close() error
Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.
func (*FilteredLevelWriter) Write ¶ added in v1.4.2
func (w *FilteredLevelWriter) Write(p []byte) (int, error)
Write writes to the underlying Writer.
func (*FilteredLevelWriter) WriteLevel ¶ added in v1.4.2
func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error)
WriteLevel calls WriteLevel of the underlying Writer only if the level is equal or above the Level.
type Formatter ¶ added in v1.4.2
type Formatter func(interface{}) string
Formatter transforms the input into a formatted string.
type FormatterByFieldName ¶ added in v1.4.2
FormatterByFieldName transforms the input into a formatted string, being able to differentiate formatting based on field name.
type GlogHandler ¶
type GlogHandler struct {
// contains filtered or unexported fields
}
GlogHandler is a log handler that mimics glog behavior.
func NewGlogHandler ¶
func NewGlogHandler(h slog.Handler) *GlogHandler
NewGlogHandler creates a GlogHandler wrapping the given handler.
func (*GlogHandler) Verbosity ¶
func (h *GlogHandler) Verbosity(level slog.Level)
Verbosity sets the global verbosity level.
func (*GlogHandler) Vmodule ¶
func (h *GlogHandler) Vmodule(pattern string) error
Vmodule sets per-module verbosity patterns.
type Hook ¶ added in v1.4.2
type Hook interface {
// Run runs the hook with the event.
Run(e *Event, level Level, message string)
}
Hook defines an interface to a log hook.
type HookFunc ¶ added in v1.4.2
HookFunc is an adaptor to allow the use of an ordinary function as a Hook.
type Level ¶
type Level int8
Level defines log levels.
const ( // DebugLevel defines debug log level. DebugLevel Level = iota // InfoLevel defines info log level. InfoLevel // WarnLevel defines warn log level. WarnLevel // ErrorLevel defines error log level. ErrorLevel // FatalLevel defines fatal log level. FatalLevel // PanicLevel defines panic log level. PanicLevel // NoLevel defines an absent log level. NoLevel // Disabled disables the logger. Disabled // TraceLevel defines trace level. TraceLevel Level = -1 )
const ( LevelTrace Level = TraceLevel LevelDebug Level = DebugLevel LevelInfo Level = InfoLevel LevelWarn Level = WarnLevel LevelError Level = ErrorLevel LevelCrit Level = FatalLevel // Aliases for backward compatibility LvlTrace = LevelTrace LvlInfo = LevelInfo LvlDebug = LevelDebug )
Level aliases for geth/logger compatibility. These are logger.Level type (int8) for use with Logger.Enabled().
func GlobalLevel ¶ added in v1.4.2
func GlobalLevel() Level
GlobalLevel returns the current global log level
func ParseLevel ¶ added in v1.4.2
ParseLevel converts a level string into a logger Level value.
func (Level) MarshalText ¶ added in v1.4.2
MarshalText implements encoding.TextMarshaler
func (*Level) UnmarshalText ¶ added in v1.4.2
UnmarshalText implements encoding.TextUnmarshaler
type LevelHook ¶ added in v1.4.2
type LevelHook struct {
NoLevelHook, TraceHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook
}
LevelHook applies a different hook for each level.
func NewLevelHook ¶ added in v1.4.2
func NewLevelHook() LevelHook
NewLevelHook returns a new LevelHook.
type LevelSampler ¶ added in v1.4.2
type LevelSampler struct {
TraceSampler, DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler
}
LevelSampler applies a different sampler for each level.
func (LevelSampler) Sample ¶ added in v1.4.2
func (s LevelSampler) Sample(lvl Level) bool
type LevelWriter ¶ added in v1.4.2
LevelWriter defines as interface a writer may implement in order to receive level information with payload.
func MultiLevelWriter ¶ added in v1.4.2
func MultiLevelWriter(writers ...io.Writer) LevelWriter
MultiLevelWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command. If some writers implement LevelWriter, their WriteLevel method will be used instead of Write.
type LevelWriterAdapter ¶ added in v1.4.2
LevelWriterAdapter adapts an io.Writer to support the LevelWriter interface.
func (LevelWriterAdapter) Close ¶ added in v1.4.2
func (lw LevelWriterAdapter) Close() error
Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.
func (LevelWriterAdapter) WriteLevel ¶ added in v1.4.2
func (lw LevelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error)
WriteLevel simply writes everything to the adapted writer, ignoring the level.
type LogArrayMarshaler ¶ added in v1.4.2
type LogArrayMarshaler interface {
MarshalLogArray(a *Array)
}
LogArrayMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Array methods.
type LogObjectMarshaler ¶ added in v1.4.2
type LogObjectMarshaler interface {
MarshalLogObject(e *Event)
}
LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Object methods.
type Logger ¶
type Logger interface {
// Geth-style variadic logging methods
Trace(msg string, ctx ...interface{})
Debug(msg string, ctx ...interface{})
Info(msg string, ctx ...interface{})
Warn(msg string, ctx ...interface{})
Error(msg string, ctx ...interface{})
Fatal(msg string, ctx ...interface{})
Panic(msg string, ctx ...interface{})
Crit(msg string, ctx ...interface{})
Verbo(msg string, ctx ...interface{})
Log(level Level, msg string, ctx ...interface{})
// Context/child loggers
With() Context
New(ctx ...interface{}) Logger
Output(w io.Writer) Logger
// Level control
Level(lvl Level) Logger
GetLevel() Level
Enabled(ctx context.Context, level slog.Level) bool
// Zero-allocation event-based logging
TraceEvent() *Event
DebugEvent() *Event
InfoEvent() *Event
WarnEvent() *Event
ErrorEvent() *Event
FatalEvent() *Event
PanicEvent() *Event
Err(err error) *Event
WithLevel(level Level) *Event
LogEvent() *Event
// Utilities
Sample(s Sampler) Logger
Hook(hooks ...Hook) Logger
Print(v ...interface{})
Printf(format string, v ...interface{})
Write(p []byte) (n int, err error)
// Configuration
SetLogLevel(level string) error
RecoverAndPanic(fn func())
// IsZero returns true if the logger is disabled or uninitialized.
IsZero() bool
}
Logger is the primary logging interface. All logging implementations satisfy this interface. Use == nil to check for uninitialized loggers.
func Ctx ¶ added in v1.4.2
Ctx returns the Logger associated with the ctx. If no logger is associated, DefaultContextLogger is returned, unless DefaultContextLogger is nil, in which case a disabled logger is returned.
func Default ¶ added in v1.4.2
func Default() Logger
Default returns the default logger (alias for Root)
func InitLogger ¶ added in v1.4.2
func InitLogger(chainAlias string, logLevel string, jsonFormat bool, writer io.Writer) (Logger, error)
InitLogger creates a new logger with the specified configuration. This is used by EVM to initialize the VM logger.
func New ¶
func New(ctx ...interface{}) Logger
New creates a new logger with optional context key-value pairs. Usage: log.New("component", "myapp", "version", "1.0")
func NewTestLogger ¶ added in v0.1.1
NewTestLogger returns a logger suitable for testing. If a level is provided, the logger is set to that level.
type NoLog ¶ added in v0.1.2
type NoLog struct{}
NoLog is a no-op logger for use in tests or when logging is disabled.
func (NoLog) DebugEvent ¶ added in v1.4.2
func (NoLog) ErrorEvent ¶ added in v1.4.2
func (NoLog) FatalEvent ¶ added in v1.4.2
func (NoLog) PanicEvent ¶ added in v1.4.2
func (NoLog) RecoverAndPanic ¶ added in v0.1.2
func (NoLog) RecoverAndPanic(fn func())
func (NoLog) SetLogLevel ¶ added in v1.4.2
func (NoLog) TraceEvent ¶ added in v1.4.2
type RandomSampler ¶ added in v1.4.2
type RandomSampler uint32
RandomSampler use a PRNG to randomly sample an event out of N events, regardless of their level.
func (RandomSampler) Sample ¶ added in v1.4.2
func (s RandomSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type RotatingWriterConfig ¶ added in v0.1.1
type RotatingWriterConfig struct {
Directory string // Directory to write log files
MaxSize int // Maximum size in megabytes before rotating
MaxFiles int // Maximum number of old log files to retain
MaxAge int // Maximum number of days to retain old log files
Compress bool // Whether to compress old log files
}
RotatingWriterConfig configures a rotating log file writer.
type Sampler ¶ added in v1.4.2
type Sampler interface {
// Sample returns true if the event should be part of the sample, false if
// the event should be dropped.
Sample(lvl Level) bool
}
Sampler defines an interface to a log sampler.
type SlogLogger ¶ added in v1.4.2
type SlogLogger interface {
With(ctx ...interface{}) SlogLogger
New(ctx ...interface{}) SlogLogger
Log(level slog.Level, msg string, ctx ...interface{})
Trace(msg string, ctx ...interface{})
Debug(msg string, ctx ...interface{})
Info(msg string, ctx ...interface{})
Warn(msg string, ctx ...interface{})
Error(msg string, ctx ...interface{})
Crit(msg string, ctx ...interface{})
Write(level slog.Level, msg string, attrs ...interface{})
Enabled(ctx context.Context, level slog.Level) bool
Handler() slog.Handler
}
SlogLogger is a Logger interface that wraps slog for geth compatibility.
func NewLogger ¶
func NewLogger(h slog.Handler) SlogLogger
NewLogger creates a new SlogLogger with the given handler.
func NewLoggerFromHandler ¶ added in v1.1.26
func NewLoggerFromHandler(h slog.Handler) SlogLogger
NewLoggerFromHandler creates a new SlogLogger from a slog.Handler.
func SetupTerminalLogger ¶ added in v1.4.2
func SetupTerminalLogger(level slog.Level) SlogLogger
SetupTerminalLogger sets up a terminal logger with color support.
func SlogRoot ¶ added in v1.4.2
func SlogRoot() SlogLogger
SlogRoot returns the root slog-based logger.
type TerminalHandler ¶
type TerminalHandler struct {
Prefix func(r slog.Record) string
// contains filtered or unexported fields
}
TerminalHandler formats log records for human readability on a terminal.
func NewTerminalHandler ¶
func NewTerminalHandler(wr io.Writer, useColor bool) *TerminalHandler
NewTerminalHandler returns a handler which formats log records for human readability.
func NewTerminalHandlerWithLevel ¶
NewTerminalHandlerWithLevel returns a terminal handler with level filtering.
func (*TerminalHandler) ResetFieldPadding ¶
func (h *TerminalHandler) ResetFieldPadding()
type TerminalStringer ¶
type TerminalStringer interface {
TerminalString() string
}
TerminalStringer is an interface for custom terminal serialization.
type TestWriter ¶ added in v1.4.2
type TestWriter struct {
T TestingLog
// Frame skips caller frames to capture the original file and line numbers.
Frame int
}
TestWriter is a writer that writes to testing.TB.
func NewTestWriter ¶ added in v1.4.2
func NewTestWriter(t TestingLog) TestWriter
NewTestWriter creates a writer that logs to the testing.TB.
type TestingLog ¶ added in v1.4.2
type TestingLog interface {
Log(args ...interface{})
Logf(format string, args ...interface{})
Helper()
}
TestingLog is the logging interface of testing.TB.
type TriggerLevelWriter ¶ added in v1.4.2
type TriggerLevelWriter struct {
// Destination writer. If LevelWriter is provided (usually), its WriteLevel is used
// instead of Write.
io.Writer
// ConditionalLevel is the level (and below) at which lines are buffered until
// a trigger level (or higher) line is emitted. Usually this is set to DebugLevel.
ConditionalLevel Level
// TriggerLevel is the lowest level that triggers the sending of the conditional
// level lines. Usually this is set to ErrorLevel.
TriggerLevel Level
// contains filtered or unexported fields
}
TriggerLevelWriter buffers log lines at the ConditionalLevel or below until a trigger level (or higher) line is emitted. Log lines with level higher than ConditionalLevel are always written out to the destination writer. If trigger never happens, buffered log lines are never written out.
It can be used to configure "log level per request".
func (*TriggerLevelWriter) Close ¶ added in v1.4.2
func (w *TriggerLevelWriter) Close() error
Close closes the writer and returns the buffer to the pool.
func (*TriggerLevelWriter) Trigger ¶ added in v1.4.2
func (w *TriggerLevelWriter) Trigger() error
Trigger forces flushing the buffer and change the trigger state to triggered, if the writer has not already been triggered before.
func (*TriggerLevelWriter) WriteLevel ¶ added in v1.4.2
func (w *TriggerLevelWriter) WriteLevel(l Level, p []byte) (n int, err error)