Documentation
¶
Overview ¶
Package log is a high-performance and extensible logging library designed specifically for the Go programming language. It offers flexible and structured logging capabilities, including context field extraction, multi-level logging configuration, and multiple output options, making it ideal for a wide range of server-side applications.
Context field extraction can be customized:
log.StringFromContext = func(ctx context.Context) string { return "" } log.FieldsFromContext = func(ctx context.Context) []log.Field { return []log.Field{ log.String("trace_id", "0a882193682db71edd48044db54cae88"), log.String("span_id", "50ef0724418c0a66"), } }
Load configuration from a file:
err := log.RefreshFile("log.xml") if err != nil { panic(err) }
Log messages with formatted output:
log.Tracef(ctx, TagRequestOut, "hello %s", "world") log.Debugf(ctx, TagRequestOut, "hello %s", "world") log.Infof(ctx, TagRequestIn, "hello %s", "world") log.Warnf(ctx, TagRequestIn, "hello %s", "world") log.Errorf(ctx, TagRequestIn, "hello %s", "world") log.Panicf(ctx, TagRequestIn, "hello %s", "world") log.Fatalf(ctx, TagRequestIn, "hello %s", "world")
Structured logging using field functions:
log.Trace(ctx, TagRequestOut, func() []log.Field { return []log.Field{ log.Msgf("hello %s", "world"), } }) log.Debug(ctx, TagRequestOut, func() []log.Field { return []log.Field{ log.Msgf("hello %s", "world"), } }) log.Info(ctx, TagRequestIn, log.Msgf("hello %s", "world")) log.Warn(ctx, TagRequestIn, log.Msgf("hello %s", "world")) log.Error(ctx, TagRequestIn, log.Msgf("hello %s", "world")) log.Panic(ctx, TagRequestIn, log.Msgf("hello %s", "world")) log.Fatal(ctx, TagRequestIn, log.Msgf("hello %s", "world"))
Log structured fields using a map:
log.Error(ctx, TagDefault, log.Fields(map[string]any{ "key1": "value1", "key2": "value2", })...)
Index ¶
- Constants
- Variables
- func Debug(ctx context.Context, tag *Tag, fn func() []Field)
- func Debugf(ctx context.Context, tag *Tag, format string, args ...any)
- func DumpNode(node *Node, indent int, buf *bytes.Buffer)
- func Error(ctx context.Context, tag *Tag, fields ...Field)
- func Errorf(ctx context.Context, tag *Tag, format string, args ...any)
- func Fatal(ctx context.Context, tag *Tag, fields ...Field)
- func Fatalf(ctx context.Context, tag *Tag, format string, args ...any)
- func GetAllTags() []string
- func Info(ctx context.Context, tag *Tag, fields ...Field)
- func Infof(ctx context.Context, tag *Tag, format string, args ...any)
- func MapKeys[M ~map[K]V, K comparable, V any](m M) []K
- func NewPlugin(t reflect.Type, node *Node, properties map[string]string) (reflect.Value, error)
- func OrderedMapKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K
- func Panic(ctx context.Context, tag *Tag, fields ...Field)
- func Panicf(ctx context.Context, tag *Tag, format string, args ...any)
- func Ptr[T any](i T) *T
- func PutEvent(e *Event)
- func Record(ctx context.Context, level Level, tag *Tag, skip int, fields ...Field)
- func RefreshFile(fileName string) error
- func RefreshReader(input io.Reader, ext string) error
- func RegisterConverter[T any](fn Converter[T])
- func RegisterPlugin[T any](name string, typ PluginType)
- func RegisterReader(r Reader, ext ...string)
- func Trace(ctx context.Context, tag *Tag, fn func() []Field)
- func Tracef(ctx context.Context, tag *Tag, format string, args ...any)
- func Warn(ctx context.Context, tag *Tag, fields ...Field)
- func Warnf(ctx context.Context, tag *Tag, format string, args ...any)
- func WrapError(err error, format string, args ...any) error
- func WriteFields(enc Encoder, fields []Field)
- func WriteLogString(buf *bytes.Buffer, s string)
- type Appender
- type AppenderRef
- type ArrayValue
- type AsyncLoggerConfig
- type BaseAppender
- type BaseLayout
- type ConsoleAppender
- type Converter
- type DiscardAppender
- type Encoder
- type Event
- type Field
- func Any(key string, value any) Field
- func Array(key string, val ArrayValue) Field
- func Bool(key string, val bool) Field
- func BoolPtr(key string, val *bool) Field
- func Bools(key string, val []bool) Field
- func Fields(fields map[string]any) []Field
- func Float[T FloatType](key string, val T) Field
- func FloatPtr[T FloatType](key string, val *T) Field
- func Floats[T FloatType](key string, val []T) Field
- func Int[T IntType](key string, val T) Field
- func IntPtr[T IntType](key string, val *T) Field
- func Ints[T IntType](key string, val []T) Field
- func Msg(msg string) Field
- func Msgf(format string, args ...any) Field
- func Nil(key string) Field
- func Object(key string, fields ...Field) Field
- func Reflect(key string, val any) Field
- func String(key string, val string) Field
- func StringPtr(key string, val *string) Field
- func Strings(key string, val []string) Field
- func Uint[T UintType](key string, val T) Field
- func UintPtr[T UintType](key string, val *T) Field
- func Uints[T UintType](key string, val []T) Field
- type FileAppender
- type FloatType
- type HumanizeBytes
- type IntType
- type JSONEncoder
- func (enc *JSONEncoder) AppendArrayBegin()
- func (enc *JSONEncoder) AppendArrayEnd()
- func (enc *JSONEncoder) AppendBool(v bool)
- func (enc *JSONEncoder) AppendEncoderBegin()
- func (enc *JSONEncoder) AppendEncoderEnd()
- func (enc *JSONEncoder) AppendFloat64(v float64)
- func (enc *JSONEncoder) AppendInt64(v int64)
- func (enc *JSONEncoder) AppendKey(key string)
- func (enc *JSONEncoder) AppendObjectBegin()
- func (enc *JSONEncoder) AppendObjectEnd()
- func (enc *JSONEncoder) AppendReflect(v any)
- func (enc *JSONEncoder) AppendString(v string)
- func (enc *JSONEncoder) AppendUint64(u uint64)
- func (enc *JSONEncoder) Reset()
- type JSONLayout
- type Layout
- type Level
- type Lifecycle
- type Logger
- type LoggerConfig
- type Node
- type Plugin
- type PluginTag
- type PluginType
- type Reader
- type Tag
- type TextEncoder
- func (enc *TextEncoder) AppendArrayBegin()
- func (enc *TextEncoder) AppendArrayEnd()
- func (enc *TextEncoder) AppendBool(v bool)
- func (enc *TextEncoder) AppendEncoderBegin()
- func (enc *TextEncoder) AppendEncoderEnd()
- func (enc *TextEncoder) AppendFloat64(v float64)
- func (enc *TextEncoder) AppendInt64(v int64)
- func (enc *TextEncoder) AppendKey(key string)
- func (enc *TextEncoder) AppendObjectBegin()
- func (enc *TextEncoder) AppendObjectEnd()
- func (enc *TextEncoder) AppendReflect(v any)
- func (enc *TextEncoder) AppendString(v string)
- func (enc *TextEncoder) AppendUint64(v uint64)
- type TextLayout
- type UintType
- type ValueType
- type XMLReader
Constants ¶
const ( ValueTypeBool = ValueType(iota) ValueTypeInt64 ValueTypeUint64 ValueTypeFloat64 ValueTypeString ValueTypeReflect ValueTypeArray ValueTypeObject )
const MsgKey = "msg"
Variables ¶
var ( TagDef = GetTag("_def") // used when the classification of the log is unknown. TagApp = GetTag("_app") // used when representing the logs of the application. )
var Caller = func(skip int, fast bool) (file string, line int) { if !fast { _, file, line, _ = runtime.Caller(skip + 1) return } rpc := make([]uintptr, 1) n := runtime.Callers(skip+2, rpc[:]) if n < 1 { return } pc := rpc[0] if v, ok := frameMap.Load(pc); ok { e := v.(*runtime.Frame) return e.File, e.Line } frame, _ := runtime.CallersFrames(rpc).Next() frameMap.Store(pc, &frame) return frame.File, frame.Line }
Caller returns the file name and line number of the calling function. If 'fast' is true, it uses a cache to speed up the lookup.
var FieldsFromContext func(ctx context.Context) []Field
FieldsFromContext can be set to extract structured fields from the context (e.g., trace IDs, user IDs).
var OnDropEvent func(logger string, e *Event)
OnDropEvent is a callback function that is called when an event is dropped.
var Stdout io.Writer = os.Stdout
Stdout is the standard output stream used by appenders.
var StringFromContext func(ctx context.Context) string
StringFromContext can be set to extract a string from the context.
var TimeNow func(ctx context.Context) time.Time
TimeNow is a function that can be overridden to provide custom timestamp behavior (e.g., for testing).
Functions ¶
func MapKeys ¶
func MapKeys[M ~map[K]V, K comparable, V any](m M) []K
MapKeys returns the keys of the map m.
func OrderedMapKeys ¶
OrderedMapKeys returns the keys of the map m in sorted order.
func PutEvent ¶
func PutEvent(e *Event)
PutEvent resets the given Event and returns it to the pool for reuse.
func Record ¶
Record is the core function that handles publishing log events. It checks the logger level, captures caller information, gathers context fields, and sends the log event to the logger.
func RefreshFile ¶
RefreshFile loads a logging configuration from a file by its name.
func RefreshReader ¶
RefreshReader reads the configuration from an io.Reader using the reader for the given extension.
func RegisterConverter ¶
RegisterConverter Registers a converter for a specific type T.
func RegisterPlugin ¶
func RegisterPlugin[T any](name string, typ PluginType)
RegisterPlugin Registers a plugin with a given name and type.
func RegisterReader ¶
RegisterReader registers a Reader for one or more file extensions. This allows dynamic selection of parsers based on file type.
func WrapError ¶
WrapError wraps an existing error, creating a new error with hierarchical relationships.
func WriteFields ¶
WriteFields writes a slice of Field objects to the encoder.
func WriteLogString ¶
WriteLogString escapes and writes a string according to JSON rules.
Types ¶
type Appender ¶
type Appender interface { Lifecycle // Appenders must be startable and stoppable GetName() string // Returns the appender name Append(e *Event) // Handles writing a log event }
Appender is an interface that defines components that handle log output.
type AppenderRef ¶
type AppenderRef struct { Ref string `PluginAttribute:"ref"` // contains filtered or unexported fields }
AppenderRef represents a reference to an appender by name, which will be resolved and bound later.
type ArrayValue ¶
type ArrayValue interface {
EncodeArray(enc Encoder)
}
ArrayValue is an interface for types that can be encoded as array.
type AsyncLoggerConfig ¶
type AsyncLoggerConfig struct { BufferSize int `PluginAttribute:"bufferSize,default=10000"` // contains filtered or unexported fields }
AsyncLoggerConfig is an asynchronous logger configuration. It buffers log events and processes them in a separate goroutine.
func (*AsyncLoggerConfig) EnableLevel ¶
EnableLevel returns true if the specified log level is enabled.
func (*AsyncLoggerConfig) GetName ¶
func (c *AsyncLoggerConfig) GetName() string
GetName returns the name of the logger.
func (*AsyncLoggerConfig) Publish ¶
func (c *AsyncLoggerConfig) Publish(e *Event)
Publish places the event in the buffer if there's space; drops it otherwise.
func (*AsyncLoggerConfig) Start ¶
func (c *AsyncLoggerConfig) Start() error
Start initializes the asynchronous logger and starts its worker goroutine.
func (*AsyncLoggerConfig) Stop ¶
func (c *AsyncLoggerConfig) Stop()
Stop shuts down the asynchronous logger and waits for the worker goroutine to finish.
type BaseAppender ¶
type BaseAppender struct { Name string `PluginAttribute:"name"` // Appender name from config Layout Layout `PluginElement:"Layout"` // Layout defines how logs are formatted }
BaseAppender provides shared configuration and behavior for appenders.
func (*BaseAppender) Append ¶
func (c *BaseAppender) Append(e *Event)
func (*BaseAppender) GetName ¶
func (c *BaseAppender) GetName() string
func (*BaseAppender) Start ¶
func (c *BaseAppender) Start() error
func (*BaseAppender) Stop ¶
func (c *BaseAppender) Stop()
type BaseLayout ¶
type BaseLayout struct {
FileLineLength int `PluginAttribute:"fileLineLength,default=48"`
}
BaseLayout is the base class for Layout.
func (*BaseLayout) GetBuffer ¶
func (c *BaseLayout) GetBuffer() *bytes.Buffer
GetBuffer returns a buffer that can be used to format the log event.
func (*BaseLayout) GetFileLine ¶
func (c *BaseLayout) GetFileLine(e *Event) string
GetFileLine returns the file name and line number of the log event.
func (*BaseLayout) PutBuffer ¶
func (c *BaseLayout) PutBuffer(buf *bytes.Buffer)
PutBuffer puts a buffer back into the pool.
type ConsoleAppender ¶
type ConsoleAppender struct {
BaseAppender
}
ConsoleAppender writes formatted log events to stdout.
func (*ConsoleAppender) Append ¶
func (c *ConsoleAppender) Append(e *Event)
Append formats the event and writes it to standard output.
type DiscardAppender ¶
type DiscardAppender struct {
BaseAppender
}
DiscardAppender ignores all log events (no output).
type Encoder ¶
type Encoder interface { AppendEncoderBegin() AppendEncoderEnd() AppendObjectBegin() AppendObjectEnd() AppendArrayBegin() AppendArrayEnd() AppendKey(key string) AppendBool(v bool) AppendInt64(v int64) AppendUint64(v uint64) AppendFloat64(v float64) AppendString(v string) AppendReflect(v any) }
Encoder is an interface that defines methods for appending structured data elements.
type Event ¶
type Event struct { Level Level // The severity level of the log (e.g., INFO, ERROR, DEBUG) Time time.Time // The timestamp when the event occurred File string // The source file where the log was triggered Line int // The line number in the source file Tag string // A tag used to categorize the log (e.g., subsystem name) Fields []Field // Custom fields provided specifically for this log event CtxString string // The string representation of the context CtxFields []Field // Additional fields derived from the context (e.g., request ID, user ID) }
Event provides contextual information about a log message.
type Field ¶
Field represents a structured log field with a key and a value.
func Any ¶
Any creates a Field from a value of any type by inspecting its dynamic type. It dispatches to the appropriate typed constructor based on the actual value. If the type is not explicitly handled, it falls back to using Reflect.
func Array ¶
func Array(key string, val ArrayValue) Field
Array creates a Field with array type, using the ArrayValue interface.
func Object ¶
Object creates a Field containing a variadic slice of Fields, treated as a nested object.
type FileAppender ¶
type FileAppender struct { BaseAppender FileName string `PluginAttribute:"fileName"` // contains filtered or unexported fields }
FileAppender writes formatted log events to a specified file.
func (*FileAppender) Append ¶
func (c *FileAppender) Append(e *Event)
Append formats the log event and writes it to the file.
type HumanizeBytes ¶
type HumanizeBytes int
func ParseHumanizeBytes ¶
func ParseHumanizeBytes(s string) (HumanizeBytes, error)
ParseHumanizeBytes converts a human-readable byte string to an integer.
type JSONEncoder ¶
type JSONEncoder struct {
// contains filtered or unexported fields
}
JSONEncoder is a simple JSON encoder.
func NewJSONEncoder ¶
func NewJSONEncoder(buf *bytes.Buffer) *JSONEncoder
NewJSONEncoder creates a new JSONEncoder.
func (*JSONEncoder) AppendArrayBegin ¶
func (enc *JSONEncoder) AppendArrayBegin()
AppendArrayBegin writes the beginning of a JSON array.
func (*JSONEncoder) AppendArrayEnd ¶
func (enc *JSONEncoder) AppendArrayEnd()
AppendArrayEnd writes the end of a JSON array.
func (*JSONEncoder) AppendBool ¶
func (enc *JSONEncoder) AppendBool(v bool)
AppendBool writes a boolean value.
func (*JSONEncoder) AppendEncoderBegin ¶
func (enc *JSONEncoder) AppendEncoderBegin()
AppendEncoderBegin writes the start of an encoder section.
func (*JSONEncoder) AppendEncoderEnd ¶
func (enc *JSONEncoder) AppendEncoderEnd()
AppendEncoderEnd writes the end of an encoder section.
func (*JSONEncoder) AppendFloat64 ¶
func (enc *JSONEncoder) AppendFloat64(v float64)
AppendFloat64 writes a float64 value.
func (*JSONEncoder) AppendInt64 ¶
func (enc *JSONEncoder) AppendInt64(v int64)
AppendInt64 writes an int64 value.
func (*JSONEncoder) AppendKey ¶
func (enc *JSONEncoder) AppendKey(key string)
AppendKey writes a JSON key.
func (*JSONEncoder) AppendObjectBegin ¶
func (enc *JSONEncoder) AppendObjectBegin()
AppendObjectBegin writes the beginning of a JSON object.
func (*JSONEncoder) AppendObjectEnd ¶
func (enc *JSONEncoder) AppendObjectEnd()
AppendObjectEnd writes the end of a JSON object.
func (*JSONEncoder) AppendReflect ¶
func (enc *JSONEncoder) AppendReflect(v any)
AppendReflect marshals any Go value into JSON and appends it.
func (*JSONEncoder) AppendString ¶
func (enc *JSONEncoder) AppendString(v string)
AppendString writes a string value with proper escaping.
func (*JSONEncoder) AppendUint64 ¶
func (enc *JSONEncoder) AppendUint64(u uint64)
AppendUint64 writes an uint64 value.
type JSONLayout ¶
type JSONLayout struct {
BaseLayout
}
JSONLayout formats the log event as a structured JSON object.
func (*JSONLayout) ToBytes ¶
func (c *JSONLayout) ToBytes(e *Event) []byte
ToBytes converts a log event to a JSON-formatted byte slice.
type Level ¶
type Level int32
Level is an enumeration used to identify the severity of a logging event.
const ( NoneLevel Level = iota // No logging TraceLevel // Very detailed logging, typically for debugging at a granular level DebugLevel // Debugging information InfoLevel // General informational messages WarnLevel // Warnings that may indicate a potential problem ErrorLevel // Errors that allow the application to continue running PanicLevel // Severe issues that may lead to a panic FatalLevel // Critical issues that will cause application termination )
func ParseLevel ¶
ParseLevel converts a string (case-insensitive) into a corresponding Level value. Returns an error if the input string does not match any valid level.
type Lifecycle ¶
type Lifecycle interface { Start() error Stop() }
Lifecycle Optional lifecycle interface for plugin instances.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is the primary logging structure used to emit log events.
type LoggerConfig ¶
type LoggerConfig struct {
// contains filtered or unexported fields
}
LoggerConfig is a synchronous logger configuration.
func (*LoggerConfig) EnableLevel ¶
EnableLevel returns true if the specified log level is enabled.
func (*LoggerConfig) GetName ¶
func (c *LoggerConfig) GetName() string
GetName returns the name of the logger.
func (*LoggerConfig) Publish ¶
func (c *LoggerConfig) Publish(e *Event)
Publish sends the event directly to the appenders.
func (*LoggerConfig) Start ¶
func (c *LoggerConfig) Start() error
func (*LoggerConfig) Stop ¶
func (c *LoggerConfig) Stop()
type Node ¶
type Node struct { Label string // Tag name of the XML element Children []*Node // Child elements (nested tags) Attributes map[string]string // Attributes of the XML element Text string // Text content of the XML element }
Node represents a parsed XML element with a label (tag name), child nodes, and a map of attributes.
type Plugin ¶
type Plugin struct { Name string // Name of plugin Type PluginType // Type of plugin Class reflect.Type // Underlying struct type File string // Source file of registration Line int // Line number of registration }
Plugin metadata structure
type PluginTag ¶
type PluginTag string
type PluginType ¶
type PluginType string
PluginType Defines types of plugins supported by the logging system.
const ( PluginTypeAppender PluginType = "Appender" PluginTypeLayout PluginType = "Layout" PluginTypeAppenderRef PluginType = "AppenderRef" PluginTypeRoot PluginType = "Root" PluginTypeAsyncRoot PluginType = "AsyncRoot" PluginTypeLogger PluginType = "Logger" PluginTypeAsyncLogger PluginType = "AsyncLogger" )
type Tag ¶
type Tag struct {
// contains filtered or unexported fields
}
Tag is a struct representing a named logging tag. It holds a pointer to a Logger and a string identifier.
func GetTag ¶
GetTag creates or retrieves a Tag by name. If the tag does not exist, it is created and added to the global registry.
type TextEncoder ¶
type TextEncoder struct {
// contains filtered or unexported fields
}
TextEncoder encodes key-value pairs in a plain text format, optionally using JSON when inside objects/arrays.
func NewTextEncoder ¶
func NewTextEncoder(buf *bytes.Buffer, separator string) *TextEncoder
NewTextEncoder creates a new TextEncoder, using the specified separator.
func (*TextEncoder) AppendArrayBegin ¶
func (enc *TextEncoder) AppendArrayBegin()
AppendArrayBegin signals the start of a JSON array. Increments the depth and delegates to the JSON encoder.
func (*TextEncoder) AppendArrayEnd ¶
func (enc *TextEncoder) AppendArrayEnd()
AppendArrayEnd signals the end of a JSON array. Decrements the depth and resets the JSON encoder if back to top level.
func (*TextEncoder) AppendBool ¶
func (enc *TextEncoder) AppendBool(v bool)
AppendBool appends a boolean value, using JSON encoder if nested.
func (*TextEncoder) AppendEncoderBegin ¶
func (enc *TextEncoder) AppendEncoderBegin()
AppendEncoderBegin writes the start of an encoder section.
func (*TextEncoder) AppendEncoderEnd ¶
func (enc *TextEncoder) AppendEncoderEnd()
AppendEncoderEnd writes the end of an encoder section.
func (*TextEncoder) AppendFloat64 ¶
func (enc *TextEncoder) AppendFloat64(v float64)
AppendFloat64 appends a float64 value, using JSON encoder if nested.
func (*TextEncoder) AppendInt64 ¶
func (enc *TextEncoder) AppendInt64(v int64)
AppendInt64 appends an int64 value, using JSON encoder if nested.
func (*TextEncoder) AppendKey ¶
func (enc *TextEncoder) AppendKey(key string)
AppendKey appends a key for a key-value pair. If inside a JSON structure, the key is handled by the JSON encoder. Otherwise, it's written directly with proper separator handling.
func (*TextEncoder) AppendObjectBegin ¶
func (enc *TextEncoder) AppendObjectBegin()
AppendObjectBegin signals the start of a JSON object. Increments the depth and delegates to the JSON encoder.
func (*TextEncoder) AppendObjectEnd ¶
func (enc *TextEncoder) AppendObjectEnd()
AppendObjectEnd signals the end of a JSON object. Decrements the depth and resets the JSON encoder if back to top level.
func (*TextEncoder) AppendReflect ¶
func (enc *TextEncoder) AppendReflect(v any)
AppendReflect uses reflection to marshal any value as JSON. If nested, delegates to JSON encoder.
func (*TextEncoder) AppendString ¶
func (enc *TextEncoder) AppendString(v string)
AppendString appends a string value, using JSON encoder if nested.
func (*TextEncoder) AppendUint64 ¶
func (enc *TextEncoder) AppendUint64(v uint64)
AppendUint64 appends a uint64 value, using JSON encoder if nested.
type TextLayout ¶
type TextLayout struct {
BaseLayout
}
TextLayout formats the log event as a human-readable text string.
func (*TextLayout) ToBytes ¶
func (c *TextLayout) ToBytes(e *Event) []byte
ToBytes converts a log event to a formatted plain-text line.