log

package module
v1.4.3 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: BSD-3-Clause Imports: 33 Imported by: 453

README

Lux Logger

A high-performance, zero-allocation structured logging library for the Lux ecosystem. Based on zerolog with additional geth-style API support.

Features

  • Blazing fast: ~8ns/op for empty log, zero allocations
  • Zero allocation: Uses sync.Pool for Event recycling
  • Two logging styles: Chaining API + traditional API (geth-compatible)
  • Structured logging: Type-safe field constructors
  • Leveled logging: Trace, Debug, Info, Warn, Error, Fatal, Panic
  • Contextual fields: Pre-set fields via With()
  • Pretty console output: Colorized human-readable format
  • Sampling: Reduce log volume in production
  • Hooks: Custom processing for log events

Installation

go get github.com/luxfi/logger

Quick Start

Chaining API
import "github.com/luxfi/logger/log"

// Simple logging
log.Info().Msg("hello world")

// With fields
log.Info().
    Str("user", "alice").
    Int("attempt", 3).
    Msg("login successful")

// With timestamp
log.Logger = log.Output(os.Stdout).With().Timestamp().Logger()
Traditional API (geth-compatible)
import "github.com/luxfi/logger"

// Simple logging
logger.Info("hello world")

// With fields
logger.Info("login successful",
    logger.String("user", "alice"),
    logger.Int("attempt", 3),
)

// Error with stack
logger.Error("operation failed", logger.Err(err))

Performance

Zero-allocation design using sync.Pool:

BenchmarkLogEmpty-10        161256609     8.443 ns/op    0 B/op   0 allocs/op
BenchmarkLogFields-10        32669988    40.22 ns/op     0 B/op   0 allocs/op
BenchmarkLogFieldType/Str    95961300    11.68 ns/op     0 B/op   0 allocs/op
BenchmarkLogFieldType/Int    89553908    11.75 ns/op     0 B/op   0 allocs/op
BenchmarkLogFieldType/Bool   94231278    12.02 ns/op     0 B/op   0 allocs/op
BenchmarkLogFieldType/Time   69632661    18.13 ns/op     0 B/op   0 allocs/op

Comparison with other loggers:

Library Time Bytes Allocs
luxfi/logger 8 ns/op 0 B/op 0 allocs/op
zerolog 19 ns/op 0 B/op 0 allocs/op
zap 236 ns/op 0 B/op 0 allocs/op
logrus 1244 ns/op 1505 B/op 27 allocs/op

Log Levels

const (
    TraceLevel Level = -1
    DebugLevel Level = 0
    InfoLevel  Level = 1
    WarnLevel  Level = 2
    ErrorLevel Level = 3
    FatalLevel Level = 4
    PanicLevel Level = 5
)
Setting Level
// Global level
logger.SetGlobalLevel(logger.WarnLevel)

// Per-logger level
log := logger.New(os.Stdout).Level(logger.InfoLevel)

Field Types

Chaining API (on Event)
event.Str("key", "value")
event.Int("key", 42)
event.Float64("key", 3.14)
event.Bool("key", true)
event.Err(err)
event.Time("key", time.Now())
event.Dur("key", time.Second)
event.Interface("key", obj)
event.Bytes("key", []byte{})
event.Strs("key", []string{})
event.Ints("key", []int{})
Traditional API (Field constructors)
logger.String("key", "value")  // or logger.Str("key", "value")
logger.Int("key", 42)
logger.Float64("key", 3.14)
logger.Bool("key", true)
logger.Err(err)
logger.Time("key", time.Now())
logger.Duration("key", time.Second)  // or logger.Dur("key", time.Second)
logger.Any("key", obj)
logger.Binary("key", []byte{})

Context Logger

Pre-set fields for all log messages:

// Chaining API
log := logger.New(os.Stdout).With().
    Str("service", "api").
    Str("version", "1.0.0").
    Logger()

log.Info().Msg("request") // includes service and version

// Traditional API
logger.SetDefault(log)
logger.Info("request") // includes service and version

Pretty Console Output

output := logger.ConsoleWriter{Out: os.Stdout}
log := logger.New(output)

log.Info().Str("foo", "bar").Msg("Hello World")
// Output: 3:04pm INF Hello World foo=bar

Sampling

Reduce log volume:

sampled := log.Sample(&logger.BasicSampler{N: 10})
sampled.Info().Msg("logged every 10 messages")

Hooks

type SeverityHook struct{}

func (h SeverityHook) Run(e *logger.Event, level logger.Level, msg string) {
    if level != logger.NoLevel {
        e.Str("severity", level.String())
    }
}

log := logger.New(os.Stdout).Hook(SeverityHook{})

Sub-packages

  • github.com/luxfi/logger - Core package with traditional API
  • github.com/luxfi/logger/log - Global logger with chaining API

Why not just use zerolog?

  1. Package naming: logger doesn't shadow Go's log package
  2. Dual API: Both zerolog chaining and geth-style traditional logging
  3. Lux ecosystem integration: Designed for Lux blockchain projects
  4. Performance tuned: Even faster than upstream zerolog on some benchmarks

License

See LICENSE file for details.

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

View Source
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"
)
View Source
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

View Source
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
)
View Source
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)
)
View Source
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 DiscardHandler

func DiscardHandler() slog.Handler

DiscardHandler returns a no-op handler.

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

func FormatLogfmtUint64(n uint64) string

FormatLogfmtUint64 formats a uint64 as a compact logfmt string.

func FormatSlogValue

func FormatSlogValue(v slog.Value, tmp []byte) (result []byte)

FormatSlogValue formats a slog.Value for serialization to terminal.

func FromLegacyLevel

func FromLegacyLevel(lvl int) slog.Level

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 IsInternalPackage(pkg string) bool

func JSONHandler

func JSONHandler(wr io.Writer) slog.Handler

JSONHandler returns a handler which prints records in JSON format.

func JSONHandlerWithLevel

func JSONHandlerWithLevel(wr io.Writer, level slog.Leveler) slog.Handler

JSONHandlerWithLevel returns a JSON handler with level filtering.

func LevelAlignedString

func LevelAlignedString(l slog.Level) string

LevelAlignedString returns a 5-character string containing the name of a level.

func LevelString

func LevelString(l slog.Level) string

LevelString returns a string containing the name of a level.

func Log added in v1.4.2

func Log(level Level, msg string, ctx ...interface{})

Log logs at the specified level with geth-style context

func LogfmtHandler

func LogfmtHandler(wr io.Writer) slog.Handler

LogfmtHandler returns a handler which prints records in logfmt format.

func LogfmtHandlerWithLevel

func LogfmtHandlerWithLevel(wr io.Writer, level slog.Leveler) slog.Handler

LogfmtHandlerWithLevel returns a logfmt handler with level filtering.

func LvlFromString added in v1.4.2

func LvlFromString(lvlString string) (slog.Level, error)

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

func SyncWriter(w io.Writer) io.Writer

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

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

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) Bool added in v1.4.2

func (a *Array) Bool(b bool) *Array

Bool appends the val as a bool to the array.

func (*Array) Bytes added in v1.4.2

func (a *Array) Bytes(val []byte) *Array

Bytes appends the val as a string to the array.

func (*Array) Dict added in v1.4.2

func (a *Array) Dict(dict *Event) *Array

Dict adds the dict Event to the array

func (*Array) Dur added in v1.4.2

func (a *Array) Dur(d time.Duration) *Array

Dur appends d to the array.

func (*Array) Err added in v1.4.2

func (a *Array) Err(err error) *Array

Err serializes and appends the err to the array.

func (*Array) Errs added in v1.4.2

func (a *Array) Errs(errs []error) *Array

Errs serializes and appends errors to the array.

func (*Array) Float32 added in v1.4.2

func (a *Array) Float32(f float32) *Array

Float32 appends f as a float32 to the array.

func (*Array) Float64 added in v1.4.2

func (a *Array) Float64(f float64) *Array

Float64 appends f as a float64 to the array.

func (*Array) Hex added in v1.4.2

func (a *Array) Hex(val []byte) *Array

Hex appends the val as a hex string to the array.

func (*Array) IPAddr added in v1.4.2

func (a *Array) IPAddr(ip net.IP) *Array

IPAddr adds a net.IP IPv4 or IPv6 address to the array

func (*Array) IPPrefix added in v1.4.2

func (a *Array) IPPrefix(pfx net.IPNet) *Array

IPPrefix adds a net.IPNet IPv4 or IPv6 Prefix (IP + mask) to the array

func (*Array) Int added in v1.4.2

func (a *Array) Int(i int) *Array

Int appends i as a int to the array.

func (*Array) Int8 added in v1.4.2

func (a *Array) Int8(i int8) *Array

Int8 appends i as a int8 to the array.

func (*Array) Int16 added in v1.4.2

func (a *Array) Int16(i int16) *Array

Int16 appends i as a int16 to the array.

func (*Array) Int32 added in v1.4.2

func (a *Array) Int32(i int32) *Array

Int32 appends i as a int32 to the array.

func (*Array) Int64 added in v1.4.2

func (a *Array) Int64(i int64) *Array

Int64 appends i as a int64 to the array.

func (*Array) Interface added in v1.4.2

func (a *Array) Interface(i interface{}) *Array

Interface appends i marshaled using reflection.

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

func (*Array) MarshalLogArray(*Array)

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) RawJSON added in v1.4.2

func (a *Array) RawJSON(val []byte) *Array

RawJSON adds already encoded JSON to the array.

func (*Array) Str added in v1.4.2

func (a *Array) Str(val string) *Array

Str appends the val as a string to the array.

func (*Array) Time added in v1.4.2

func (a *Array) Time(t time.Time) *Array

Time appends t formatted as string using logger.TimeFieldFormat.

func (*Array) Type added in v1.4.2

func (a *Array) Type(val interface{}) *Array

Type adds the val's type using reflection to the array.

func (*Array) Uint added in v1.4.2

func (a *Array) Uint(i uint) *Array

Uint appends i as a uint to the array.

func (*Array) Uint8 added in v1.4.2

func (a *Array) Uint8(i uint8) *Array

Uint8 appends i as a uint8 to the array.

func (*Array) Uint16 added in v1.4.2

func (a *Array) Uint16(i uint16) *Array

Uint16 appends i as a uint16 to the array.

func (*Array) Uint32 added in v1.4.2

func (a *Array) Uint32(i uint32) *Array

Uint32 appends i as a uint32 to the array.

func (*Array) Uint64 added in v1.4.2

func (a *Array) Uint64(i uint64) *Array

Uint64 appends i as a uint64 to the array.

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

func (Color) Wrap added in v0.1.1

func (c Color) Wrap(s string) string

Wrap wraps the given string with ANSI color codes

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.

func (ConsoleWriter) Write added in v1.4.2

func (w ConsoleWriter) Write(p []byte) (n int, err error)

Write transforms the JSON input with formatters and appends to w.Out.

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

func (c Context) AnErr(key string, err error) Context

AnErr adds the field key with serialized err to the logger context. If err is nil, no field is added.

func (Context) Any added in v1.4.2

func (c Context) Any(key string, i interface{}) Context

Any is a wrapper around Context.Interface.

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

func (c Context) Bool(key string, b bool) Context

Bool adds the field key with val as a bool to the logger context.

func (Context) Bools added in v1.4.2

func (c Context) Bools(key string, b []bool) Context

Bools adds the field key with val as a []bool to the logger context.

func (Context) Bytes added in v1.4.2

func (c Context) Bytes(key string, val []byte) Context

Bytes adds the field key with val as a []byte to the logger context.

func (Context) Caller added in v1.4.2

func (c Context) Caller() Context

Caller adds the file:line of the caller with the logger.CallerFieldName key.

func (Context) CallerWithSkipFrameCount added in v1.4.2

func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context

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

func (c Context) CreateArray() *Array

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

func (c Context) CreateDict() *Event

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

func (c Context) Ctx(ctx context.Context) Context

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) Dict added in v1.4.2

func (c Context) Dict(key string, dict *Event) Context

Dict adds the field key with the dict to the logger context.

func (Context) Dur added in v1.4.2

func (c Context) Dur(key string, d time.Duration) Context

Dur adds the field key with d divided by unit and stored as a float.

func (Context) Durs added in v1.4.2

func (c Context) Durs(key string, d []time.Duration) Context

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

func (c Context) Err(err error) Context

Err adds the field "error" with serialized err to the logger context.

func (Context) Errs added in v1.4.2

func (c Context) Errs(key string, errs []error) Context

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

func (c Context) Fields(fields interface{}) Context

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

func (c Context) Float32(key string, f float32) Context

Float32 adds the field key with f as a float32 to the logger context.

func (Context) Float64 added in v1.4.2

func (c Context) Float64(key string, f float64) Context

Float64 adds the field key with f as a float64 to the logger context.

func (Context) Floats32 added in v1.4.2

func (c Context) Floats32(key string, f []float32) Context

Floats32 adds the field key with f as a []float32 to the logger context.

func (Context) Floats64 added in v1.4.2

func (c Context) Floats64(key string, f []float64) Context

Floats64 adds the field key with f as a []float64 to the logger context.

func (Context) Hex added in v1.4.2

func (c Context) Hex(key string, val []byte) Context

Hex adds the field key with val as a hex string to the logger context.

func (Context) IPAddr added in v1.4.2

func (c Context) IPAddr(key string, ip net.IP) Context

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

func (c Context) IPAddrs(key string, ip []net.IP) Context

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

func (c Context) IPPrefix(key string, pfx net.IPNet) Context

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

func (c Context) IPPrefixes(key string, pfx []net.IPNet) Context

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) Int added in v1.4.2

func (c Context) Int(key string, i int) Context

Int adds the field key with i as a int to the logger context.

func (Context) Int8 added in v1.4.2

func (c Context) Int8(key string, i int8) Context

Int8 adds the field key with i as a int8 to the logger context.

func (Context) Int16 added in v1.4.2

func (c Context) Int16(key string, i int16) Context

Int16 adds the field key with i as a int16 to the logger context.

func (Context) Int32 added in v1.4.2

func (c Context) Int32(key string, i int32) Context

Int32 adds the field key with i as a int32 to the logger context.

func (Context) Int64 added in v1.4.2

func (c Context) Int64(key string, i int64) Context

Int64 adds the field key with i as a int64 to the logger context.

func (Context) Interface added in v1.4.2

func (c Context) Interface(key string, i interface{}) Context

Interface adds the field key with obj marshaled using reflection.

func (Context) Ints added in v1.4.2

func (c Context) Ints(key string, i []int) Context

Ints adds the field key with i as a []int to the logger context.

func (Context) Ints8 added in v1.4.2

func (c Context) Ints8(key string, i []int8) Context

Ints8 adds the field key with i as a []int8 to the logger context.

func (Context) Ints16 added in v1.4.2

func (c Context) Ints16(key string, i []int16) Context

Ints16 adds the field key with i as a []int16 to the logger context.

func (Context) Ints32 added in v1.4.2

func (c Context) Ints32(key string, i []int32) Context

Ints32 adds the field key with i as a []int32 to the logger context.

func (Context) Ints64 added in v1.4.2

func (c Context) Ints64(key string, i []int64) Context

Ints64 adds the field key with i as a []int64 to the logger context.

func (Context) Logger added in v1.4.2

func (c Context) Logger() Logger

Logger returns the logger with the context previously set.

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

func (c Context) RawJSON(key string, b []byte) Context

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) Reset added in v1.4.2

func (c Context) Reset() Context

Reset removes all the context fields.

func (Context) Stack added in v1.4.2

func (c Context) Stack() Context

Stack enables stack trace printing for the error passed to Err().

func (Context) Str added in v1.4.2

func (c Context) Str(key, val string) Context

Str adds the field key with val as a string to the logger context.

func (Context) Stringer added in v1.4.2

func (c Context) Stringer(key string, val fmt.Stringer) Context

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

func (c Context) Stringers(key string, vals []fmt.Stringer) Context

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

func (c Context) Strs(key string, vals []string) Context

Strs adds the field key with val as a string to the logger context.

func (Context) Time added in v1.4.2

func (c Context) Time(key string, t time.Time) Context

Time adds the field key with t formatted as string using logger.TimeFieldFormat.

func (Context) Times added in v1.4.2

func (c Context) Times(key string, t []time.Time) Context

Times adds the field key with t formatted as string using logger.TimeFieldFormat.

func (Context) Timestamp added in v1.4.2

func (c Context) Timestamp() Context

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) Type added in v1.4.2

func (c Context) Type(key string, val interface{}) Context

Type adds the field key with val's type using reflection.

func (Context) Uint added in v1.4.2

func (c Context) Uint(key string, i uint) Context

Uint adds the field key with i as a uint to the logger context.

func (Context) Uint8 added in v1.4.2

func (c Context) Uint8(key string, i uint8) Context

Uint8 adds the field key with i as a uint8 to the logger context.

func (Context) Uint16 added in v1.4.2

func (c Context) Uint16(key string, i uint16) Context

Uint16 adds the field key with i as a uint16 to the logger context.

func (Context) Uint32 added in v1.4.2

func (c Context) Uint32(key string, i uint32) Context

Uint32 adds the field key with i as a uint32 to the logger context.

func (Context) Uint64 added in v1.4.2

func (c Context) Uint64(key string, i uint64) Context

Uint64 adds the field key with i as a uint64 to the logger context.

func (Context) Uints added in v1.4.2

func (c Context) Uints(key string, i []uint) Context

Uints adds the field key with i as a []uint to the logger context.

func (Context) Uints8 added in v1.4.2

func (c Context) Uints8(key string, i []uint8) Context

Uints8 adds the field key with i as a []uint8 to the logger context.

func (Context) Uints16 added in v1.4.2

func (c Context) Uints16(key string, i []uint16) Context

Uints16 adds the field key with i as a []uint16 to the logger context.

func (Context) Uints32 added in v1.4.2

func (c Context) Uints32(key string, i []uint32) Context

Uints32 adds the field key with i as a []uint32 to the logger context.

func (Context) Uints64 added in v1.4.2

func (c Context) Uints64(key string, i []uint64) Context

Uints64 adds the field key with i as a []uint64 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

func (e *Event) AnErr(key string, err error) *Event

AnErr adds the field key with serialized err to the *Event context. If err is nil, no field is added.

func (*Event) Any added in v1.4.2

func (e *Event) Any(key string, i interface{}) *Event

Any is a wrapper around Event.Interface.

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

func (e *Event) Bool(key string, b bool) *Event

Bool adds the field key with val as a bool to the *Event context.

func (*Event) Bools added in v1.4.2

func (e *Event) Bools(key string, b []bool) *Event

Bools adds the field key with val as a []bool to the *Event context.

func (*Event) Bytes added in v1.4.2

func (e *Event) Bytes(key string, val []byte) *Event

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

func (e *Event) Caller(skip ...int) *Event

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

func (e *Event) CallerSkipFrame(skip int) *Event

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

func (e *Event) CreateArray() *Array

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

func (e *Event) CreateDict() *Event

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

func (e *Event) Ctx(ctx context.Context) *Event

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

func (e *Event) Dict(key string, dict *Event) *Event

Dict adds the field key with a dict to the event context. Use e.CreateDict() to create the dictionary.

func (*Event) Discard added in v1.4.2

func (e *Event) Discard() *Event

Discard disables the event so Msg(f) won't print it.

func (*Event) Dur added in v1.4.2

func (e *Event) Dur(key string, d time.Duration) *Event

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

func (e *Event) Durs(key string, d []time.Duration) *Event

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

func (e *Event) Enabled() bool

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

func (e *Event) Err(err error) *Event

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

func (e *Event) Errs(key string, errs []error) *Event

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

func (e *Event) Fields(fields interface{}) *Event

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

func (e *Event) Float32(key string, f float32) *Event

Float32 adds the field key with f as a float32 to the *Event context.

func (*Event) Float64 added in v1.4.2

func (e *Event) Float64(key string, f float64) *Event

Float64 adds the field key with f as a float64 to the *Event context.

func (*Event) Floats32 added in v1.4.2

func (e *Event) Floats32(key string, f []float32) *Event

Floats32 adds the field key with f as a []float32 to the *Event context.

func (*Event) Floats64 added in v1.4.2

func (e *Event) Floats64(key string, f []float64) *Event

Floats64 adds the field key with f as a []float64 to the *Event context.

func (*Event) Func added in v1.4.2

func (e *Event) Func(f func(e *Event)) *Event

Func allows an anonymous func to run only if the event is enabled.

func (*Event) GetCtx added in v1.4.2

func (e *Event) GetCtx() context.Context

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

func (e *Event) Hex(key string, val []byte) *Event

Hex adds the field key with val as a hex string to the *Event context.

func (*Event) IPAddr added in v1.4.2

func (e *Event) IPAddr(key string, ip net.IP) *Event

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

func (e *Event) IPAddrs(key string, ip []net.IP) *Event

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

func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event

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

func (e *Event) IPPrefixes(key string, pfx []net.IPNet) *Event

IPPrefixes the field key with pfx as a net.IPNet array of IPv4 or IPv6 Prefixes (address and mask) to the event

func (*Event) Int added in v1.4.2

func (e *Event) Int(key string, i int) *Event

Int adds the field key with i as a int to the *Event context.

func (*Event) Int8 added in v1.4.2

func (e *Event) Int8(key string, i int8) *Event

Int8 adds the field key with i as a int8 to the *Event context.

func (*Event) Int16 added in v1.4.2

func (e *Event) Int16(key string, i int16) *Event

Int16 adds the field key with i as a int16 to the *Event context.

func (*Event) Int32 added in v1.4.2

func (e *Event) Int32(key string, i int32) *Event

Int32 adds the field key with i as a int32 to the *Event context.

func (*Event) Int64 added in v1.4.2

func (e *Event) Int64(key string, i int64) *Event

Int64 adds the field key with i as a int64 to the *Event context.

func (*Event) Interface added in v1.4.2

func (e *Event) Interface(key string, i interface{}) *Event

Interface adds the field key with i marshaled using reflection.

func (*Event) Ints added in v1.4.2

func (e *Event) Ints(key string, i []int) *Event

Ints adds the field key with i as a []int to the *Event context.

func (*Event) Ints8 added in v1.4.2

func (e *Event) Ints8(key string, i []int8) *Event

Ints8 adds the field key with i as a []int8 to the *Event context.

func (*Event) Ints16 added in v1.4.2

func (e *Event) Ints16(key string, i []int16) *Event

Ints16 adds the field key with i as a []int16 to the *Event context.

func (*Event) Ints32 added in v1.4.2

func (e *Event) Ints32(key string, i []int32) *Event

Ints32 adds the field key with i as a []int32 to the *Event context.

func (*Event) Ints64 added in v1.4.2

func (e *Event) Ints64(key string, i []int64) *Event

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

func (e *Event) Msg(msg string)

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) MsgFunc added in v1.4.2

func (e *Event) MsgFunc(createMsg func() string)

func (*Event) Msgf added in v1.4.2

func (e *Event) Msgf(format string, v ...interface{})

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

func (e *Event) RawCBOR(key string, b []byte) *Event

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

func (e *Event) RawJSON(key string, b []byte) *Event

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

func (e *Event) Stack() *Event

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

func (e *Event) Str(key, val string) *Event

Str adds the field key with val as a string to the *Event context.

func (*Event) Stringer added in v1.4.2

func (e *Event) Stringer(key string, val fmt.Stringer) *Event

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

func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event

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

func (e *Event) Strs(key string, vals []string) *Event

Strs adds the field key with vals as a []string to the *Event context.

func (*Event) Time added in v1.4.2

func (e *Event) Time(key string, t time.Time) *Event

Time adds the field key with t formatted as string using logger.TimeFieldFormat.

func (*Event) TimeDiff added in v1.4.2

func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event

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

func (e *Event) Times(key string, t []time.Time) *Event

Times adds the field key with t formatted as string using logger.TimeFieldFormat.

func (*Event) Timestamp added in v1.4.2

func (e *Event) Timestamp() *Event

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) Type added in v1.4.2

func (e *Event) Type(key string, val interface{}) *Event

Type adds the field key with val's type using reflection.

func (*Event) Uint added in v1.4.2

func (e *Event) Uint(key string, i uint) *Event

Uint adds the field key with i as a uint to the *Event context.

func (*Event) Uint8 added in v1.4.2

func (e *Event) Uint8(key string, i uint8) *Event

Uint8 adds the field key with i as a uint8 to the *Event context.

func (*Event) Uint16 added in v1.4.2

func (e *Event) Uint16(key string, i uint16) *Event

Uint16 adds the field key with i as a uint16 to the *Event context.

func (*Event) Uint32 added in v1.4.2

func (e *Event) Uint32(key string, i uint32) *Event

Uint32 adds the field key with i as a uint32 to the *Event context.

func (*Event) Uint64 added in v1.4.2

func (e *Event) Uint64(key string, i uint64) *Event

Uint64 adds the field key with i as a uint64 to the *Event context.

func (*Event) Uints added in v1.4.2

func (e *Event) Uints(key string, i []uint) *Event

Uints adds the field key with i as a []int to the *Event context.

func (*Event) Uints8 added in v1.4.2

func (e *Event) Uints8(key string, i []uint8) *Event

Uints8 adds the field key with i as a []int8 to the *Event context.

func (*Event) Uints16 added in v1.4.2

func (e *Event) Uints16(key string, i []uint16) *Event

Uints16 adds the field key with i as a []int16 to the *Event context.

func (*Event) Uints32 added in v1.4.2

func (e *Event) Uints32(key string, i []uint32) *Event

Uints32 adds the field key with i as a []int32 to the *Event context.

func (*Event) Uints64 added in v1.4.2

func (e *Event) Uints64(key string, i []uint64) *Event

Uints64 adds the field key with i as a []int64 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

func NewFactoryWithConfig(config Config) Factory

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 AnErr added in v1.4.2

func AnErr(key string, err error) Field

func Any added in v0.1.2

func Any(key string, val interface{}) Field

func Binary added in v0.1.2

func Binary(key string, val []byte) Field

func Bool added in v0.1.2

func Bool(key string, val bool) Field

func Bools added in v1.4.2

func Bools(key string, val []bool) Field

func ByteString added in v0.1.2

func ByteString(key string, val []byte) Field

func Dur added in v1.4.2

func Dur(key string, val time.Duration) Field

func Duration added in v0.1.2

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

func Durations added in v1.4.2

func Durations(key string, val []time.Duration) Field

func Err added in v0.1.2

func Err(err error) Field

func Float32 added in v0.1.2

func Float32(key string, val float32) Field

func Float64 added in v0.1.2

func Float64(key string, val float64) Field

func Float64s added in v1.4.2

func Float64s(key string, val []float64) Field

func Int added in v0.1.2

func Int(key string, val int) Field

func Int8 added in v0.1.2

func Int8(key string, val int8) Field

func Int16 added in v0.1.2

func Int16(key string, val int16) Field

func Int32 added in v0.1.2

func Int32(key string, val int32) Field

func Int64 added in v0.1.2

func Int64(key string, val int64) Field

func Int64s added in v1.4.2

func Int64s(key string, val []int64) Field

func Ints added in v1.4.2

func Ints(key string, val []int) Field

func NamedErr added in v1.4.2

func NamedErr(key string, err error) Field

func Reflect added in v0.1.2

func Reflect(key string, val interface{}) Field

Reflect returns a Field that uses reflection for complex types.

func Stack added in v0.1.2

func Stack(key string) Field

Stack returns a Field with the current stack trace.

func Str added in v1.4.2

func Str(key, val string) Field

Short-form aliases (matching chaining API style)

func String added in v0.1.2

func String(key, val string) Field

Field constructors for geth-style logging

func Stringer added in v0.1.1

func Stringer(key string, val fmt.Stringer) Field

func Strings added in v0.1.2

func Strings(key string, val []string) Field

Slice field constructors

func Time added in v0.1.2

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

func Times added in v1.4.2

func Times(key string, val []time.Time) Field

func Uint added in v0.1.2

func Uint(key string, val uint) Field

func Uint8 added in v0.1.2

func Uint8(key string, val uint8) Field

func Uint16 added in v0.1.2

func Uint16(key string, val uint16) Field

func Uint32 added in v0.1.2

func Uint32(key string, val uint32) Field

func Uint64 added in v0.1.2

func Uint64(key string, val uint64) Field

func Uint64s added in v1.4.2

func Uint64s(key string, val []uint64) Field

func UserString added in v0.1.1

func UserString(key, val string) Field

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

type FormatterByFieldName func(interface{}, string) string

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

func (h *GlogHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*GlogHandler) Handle

func (h *GlogHandler) Handle(ctx context.Context, r slog.Record) error

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.

func (*GlogHandler) WithAttrs

func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*GlogHandler) WithGroup

func (h *GlogHandler) WithGroup(name string) slog.Handler

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

type HookFunc func(e *Event, level Level, message string)

HookFunc is an adaptor to allow the use of an ordinary function as a Hook.

func (HookFunc) Run added in v1.4.2

func (h HookFunc) Run(e *Event, level Level, message string)

Run implements the Hook interface.

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

func ParseLevel(levelStr string) (Level, error)

ParseLevel converts a level string into a logger Level value.

func ToLevel added in v0.1.1

func ToLevel(s string) (Level, error)

ToLevel parses a level string and returns the corresponding Level.

func (Level) MarshalText added in v1.4.2

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler

func (Level) String added in v1.4.2

func (l Level) String() string

func (*Level) UnmarshalText added in v1.4.2

func (l *Level) UnmarshalText(text []byte) error

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.

func (LevelHook) Run added in v1.4.2

func (h LevelHook) Run(e *Event, level Level, message string)

Run implements the Hook interface.

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

type LevelWriter interface {
	io.Writer
	WriteLevel(level Level, p []byte) (n int, err error)
}

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

type LevelWriterAdapter struct {
	io.Writer
}

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 LogFormat added in v1.4.2

type LogFormat int

LogFormat represents the format of log output.

const (
	// Plain is plain text format.
	Plain LogFormat = iota
	// JSON is JSON format.
	JSON
	// Auto detects terminal and uses colors if appropriate.
	Auto
	// Colors forces color output.
	Colors
)

func ToFormat added in v0.1.1

func ToFormat(s string, fd uintptr) (LogFormat, error)

ToFormat parses a format string and returns the corresponding LogFormat. The fd parameter is reserved for future use (e.g., terminal detection).

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

func Ctx(ctx context.Context) Logger

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 NewNoOpLogger

func NewNoOpLogger() Logger

NewNoOpLogger returns a disabled logger.

func NewTestLogger added in v0.1.1

func NewTestLogger(level ...Level) Logger

NewTestLogger returns a logger suitable for testing. If a level is provided, the logger is set to that level.

func NewWriter added in v1.4.2

func NewWriter(w io.Writer) Logger

NewWriter creates a logger with a specific output writer.

func Noop added in v1.4.2

func Noop() Logger

Noop returns a disabled logger. Use this for optional logger parameters. Example: func DoWork(logger log.Logger) { if logger == nil { logger = log.Noop() } }

func Root

func Root() Logger

Root returns the default logger

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) Crit added in v0.1.2

func (NoLog) Crit(string, ...interface{})

func (NoLog) Debug added in v0.1.2

func (NoLog) Debug(string, ...interface{})

func (NoLog) DebugEvent added in v1.4.2

func (NoLog) DebugEvent() *Event

func (NoLog) Enabled added in v0.1.2

func (NoLog) Enabled(context.Context, slog.Level) bool

func (NoLog) Err added in v1.4.2

func (NoLog) Err(error) *Event

func (NoLog) Error added in v0.1.2

func (NoLog) Error(string, ...interface{})

func (NoLog) ErrorEvent added in v1.4.2

func (NoLog) ErrorEvent() *Event

func (NoLog) Fatal added in v0.1.2

func (NoLog) Fatal(string, ...interface{})

func (NoLog) FatalEvent added in v1.4.2

func (NoLog) FatalEvent() *Event

func (NoLog) GetLevel added in v0.1.2

func (NoLog) GetLevel() Level

func (NoLog) Hook added in v1.4.2

func (NoLog) Hook(...Hook) Logger

func (NoLog) Info added in v0.1.2

func (NoLog) Info(string, ...interface{})

func (NoLog) InfoEvent added in v1.4.2

func (NoLog) InfoEvent() *Event

func (NoLog) IsZero added in v1.4.2

func (NoLog) IsZero() bool

func (NoLog) Level added in v1.4.2

func (NoLog) Level(Level) Logger

func (NoLog) Log added in v0.1.2

func (NoLog) Log(Level, string, ...interface{})

func (NoLog) LogEvent added in v1.4.2

func (NoLog) LogEvent() *Event

func (NoLog) New added in v0.1.2

func (NoLog) New(...interface{}) Logger

func (NoLog) Output added in v1.4.2

func (NoLog) Output(io.Writer) Logger

func (NoLog) Panic added in v1.4.2

func (NoLog) Panic(string, ...interface{})

func (NoLog) PanicEvent added in v1.4.2

func (NoLog) PanicEvent() *Event

func (NoLog) Print added in v1.4.2

func (NoLog) Print(...interface{})

func (NoLog) Printf added in v1.4.2

func (NoLog) Printf(string, ...interface{})

func (NoLog) RecoverAndPanic added in v0.1.2

func (NoLog) RecoverAndPanic(fn func())

func (NoLog) Sample added in v1.4.2

func (NoLog) Sample(Sampler) Logger

func (NoLog) SetLogLevel added in v1.4.2

func (NoLog) SetLogLevel(string) error

func (NoLog) Trace added in v0.1.2

func (NoLog) Trace(string, ...interface{})

func (NoLog) TraceEvent added in v1.4.2

func (NoLog) TraceEvent() *Event

func (NoLog) Verbo added in v0.1.2

func (NoLog) Verbo(string, ...interface{})

func (NoLog) Warn added in v0.1.2

func (NoLog) Warn(string, ...interface{})

func (NoLog) WarnEvent added in v1.4.2

func (NoLog) WarnEvent() *Event

func (NoLog) With added in v0.1.2

func (NoLog) With() Context

func (NoLog) WithLevel added in v1.4.2

func (NoLog) WithLevel(Level) *Event

func (NoLog) Write added in v0.1.2

func (NoLog) Write(p []byte) (int, error)

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

func NewTerminalHandlerWithLevel(wr io.Writer, lvl slog.Leveler, useColor bool) *TerminalHandler

NewTerminalHandlerWithLevel returns a terminal handler with level filtering.

func (*TerminalHandler) Enabled

func (h *TerminalHandler) Enabled(_ context.Context, level slog.Level) bool

func (*TerminalHandler) Handle

func (h *TerminalHandler) Handle(_ context.Context, r slog.Record) error

func (*TerminalHandler) ResetFieldPadding

func (h *TerminalHandler) ResetFieldPadding()

func (*TerminalHandler) WithAttrs

func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*TerminalHandler) WithGroup

func (h *TerminalHandler) WithGroup(name string) slog.Handler

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.

func (TestWriter) Write added in v1.4.2

func (t TestWriter) Write(p []byte) (n int, err error)

Write to 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)

Directories

Path Synopsis
internal
Package level provides log level constants for compatibility with existing code.
Package level provides log level constants for compatibility with existing code.

Jump to

Keyboard shortcuts

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