Documentation
¶
Overview ¶
Package log is a high-performance and extensible logging library designed specifically for the Go programming language. It provides flexible and structured logging capabilities, including context field extraction, multi-level logging configuration, and multiple output options, making it ideal for server-side applications.
## Core Concepts:
Tags:
Tags are a core concept in the log package used to categorize logs. By registering a tag via the `RegisterTag` function, you can use regular expressions to match the user-defined tags. This approach allows for a unified API for logging without explicitly creating logger instances. Even third-party libraries can write logs without setting up a logger object.
Loggers:
A Logger is the object that actually handles the logging process. You can obtain a logger instance using the `GetLogger` function, which is mainly provided for compatibility with legacy projects. This allows you to directly retrieve a logger by its name and log pre-formatted messages using the `Write` function.
Context Field Extraction:
Contextual data can be extracted and included in log entries via configurable functions: - `log.StringFromContext`: Extracts a string value (e.g., a request ID) from the context. - `log.FieldsFromContext`: Returns a list of structured fields from the context, such as trace IDs or user IDs.
Configuration from File:
The `log.RefreshFile` function allows loading the logger's configuration from an external file (e.g., yaml or JSON).
Logger Initialization and Logging:
- Using `GetLogger`, you can fetch a logger instance (often for compatibility with older systems). - You can also register custom tags using `RegisterTag` to classify logs according to your needs.
Logging Messages:
The package provides various logging functions, such as `Tracef`, `Debugf`, `Infof`, `Warnf`, etc., which log messages at different levels (e.g., Trace, Debug, Info, Warn). These functions can either accept structured fields or formatted messages.
Structured Logging:
The logger also supports structured logging, where fields are captured as key-value pairs and logged with the message. The fields can be provided directly in the log functions or through a map.
## Examples:
Using a pre-registered tag:
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")
Using structured fields:
log.Trace(ctx, TagRequestOut, func() []log.Field {
return []log.Field{
log.Msgf("hello %s", "world"),
}
})
log.Error(ctx, TagRequestIn, log.FieldsFromMap(map[string]any{
"key1": "value1",
"key2": "value2",
}))
Index ¶
- Constants
- Variables
- func BuildTag(mainType, subType, action string) string
- func Debug(ctx context.Context, tag *Tag, fn func() []Field)
- func Debugf(ctx context.Context, tag *Tag, format string, args ...any)
- func Destroy()
- func EncodeFields(enc Encoder, fields []Field)
- func Error(ctx context.Context, tag *Tag, fields ...Field)
- func Errorf(ctx context.Context, tag *Tag, format string, args ...any)
- func FastCaller(skip int) (file string, line int)
- 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 NewPlugin(t reflect.Type, prefix string, s flatten.Storage) (reflect.Value, error)
- func Panic(ctx context.Context, tag *Tag, fields ...Field)
- func Panicf(ctx context.Context, tag *Tag, format string, args ...any)
- func PutEvent(e *Event)
- func Record(ctx context.Context, level Level, tag *Tag, skip int, fields ...Field)
- func Refresh(s flatten.Storage) error
- func RegisterConverter[T any](fn Converter[T])
- func RegisterPlugin[T any](name string)
- func RegisterProperty(key string, val func(string) error)
- func ToStorage(m map[string]string) (map[string]string, error)
- 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 WriteLogString(buf *bytes.Buffer, s string)
- type Appender
- type AppenderBase
- type AppenderRef
- type AppenderRefs
- type ArrayValue
- type AsyncLogger
- type BaseLayout
- type BufferFullPolicy
- type CallerType
- type ConsoleAppender
- type ConsoleLogger
- type Converter
- type DiscardAppender
- type DiscardLogger
- 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 FieldsFromMap(m 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 FileLogger
- 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 JSONTokenType
- type Layout
- type Level
- type LevelRange
- type Lifecycle
- type Logger
- type LoggerBase
- type LoggerWrapper
- type Plugin
- type PluginTag
- type RollingFileAppender
- type RollingFileLogger
- type RollingFileWriter
- type SyncLogger
- 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
Constants ¶
const ( ValueTypeBool = ValueType(iota) ValueTypeInt64 ValueTypeUint64 ValueTypeFloat64 ValueTypeString ValueTypeReflect ValueTypeArray ValueTypeObject ValueTypeFromMap )
const ( BufferFullPolicyBlock = BufferFullPolicy(0) // Block until space is available BufferFullPolicyDiscard = BufferFullPolicy(1) // Drop the new event or data BufferFullPolicyDiscardOldest = BufferFullPolicy(2) // Drop the oldest event or data )
const MsgKey = "msg"
const RootLoggerName = "root"
RootLoggerName defines the reserved name for the root logger.
Variables ¶
var ( // TimeNow is an overrideable function to provide custom timestamps. // For example, this can be replaced during testing to return a fixed time. TimeNow func(ctx context.Context) time.Time // StringFromContext is an optional hook to extract a string (e.g., trace ID) // from the context. This string will be attached to the log event. StringFromContext func(ctx context.Context) string // FieldsFromContext is an optional hook to extract structured fields // (e.g., trace ID, span ID, or request metadata) from the context. FieldsFromContext func(ctx context.Context) []Field )
var ( // TagAppDef is the default tag for application-related logs. TagAppDef = RegisterAppTag("def", "") // TagBizDef is the default tag for business-related logs. TagBizDef = RegisterBizTag("def", "") )
var ( NoneLevel = RegisterLevel(0, "NONE") // No logging TraceLevel = RegisterLevel(100, "TRACE") // Very detailed logging, typically used for debugging DebugLevel = RegisterLevel(200, "DEBUG") // Debugging information useful during development InfoLevel = RegisterLevel(300, "INFO") // General informational messages about application progress WarnLevel = RegisterLevel(400, "WARN") // Warnings about potential issues or unusual situations ErrorLevel = RegisterLevel(500, "ERROR") // Errors that allow the application to continue running PanicLevel = RegisterLevel(600, "PANIC") // Severe issues that may cause a panic in the application FatalLevel = RegisterLevel(700, "FATAL") // Critical issues that will terminate the application MaxLevel = RegisterLevel(999, "MAX") // Maximum level (used as the upper bound for comparisons) )
var (
BufferCap atomic.Int32 // Maximum buffer capacity allowed for reuse
)
var Stdout io.Writer = os.Stdout
Stdout is the standard output stream used by appenders.
Functions ¶
func BuildTag ¶ added in v0.0.4
BuildTag constructs a structured tag string from main type, sub type, and action. The format is:
_<mainType>_<subType> _<mainType>_<subType>_<action>
Example:
BuildTag("app", "startup", "init") -> "_app_startup_init"
func Debug ¶
Debug logs a message at DebugLevel using a lazy field generator. The generator function is only invoked if the level is enabled.
func Destroy ¶ added in v0.0.5
func Destroy()
Destroy gracefully shuts down all loggers and appenders, releasing resources and resetting the global state.
func EncodeFields ¶ added in v0.0.10
EncodeFields encodes a slice of Fields into the Encoder.
func FastCaller ¶ added in v0.1.0
FastCaller returns the file name and line number of the calling function. It uses a cache to speed up the lookup.
func PutEvent ¶
func PutEvent(e *Event)
PutEvent resets the given Event and returns it to the pool for reuse.
func RegisterConverter ¶
RegisterConverter registers a custom converter for type T.
func RegisterPlugin ¶
RegisterPlugin registers a plugin struct type with a given name and plugin type.
func RegisterProperty ¶ added in v0.0.5
RegisterProperty registers a property setter with a given key.
func ToStorage ¶
ToStorage converts a flattened string map into a *flatten.Storage instance. It interprets keys with a "!" suffix as nested map structures, parsing their values using expr.Parse() and inserting them under a composite key.
Example:
Input:
map[string]string{
"app.name": "MyApp",
"db!": "{host: localhost, port: 5432}",
}
Output:
flatten.Storage{
"app.name": "MyApp",
"db.host": "localhost",
"db.port": "5432",
}
func Trace ¶
Trace logs a message at TraceLevel using a lazy field generator. The generator function is only invoked if the level is enabled.
func WriteLogString ¶
WriteLogString escapes and writes a string according to JSON rules.
Types ¶
type Appender ¶
type Appender interface {
Lifecycle // Start/Stop methods for resource management
GetName() string // Returns the appender's name
Append(e *Event) // Handles writing a log event
Write(b []byte) // Directly writes a byte slice
ConcurrentSafe() bool // Returns true if the appender is concurrent-safe
}
Appender defines components that handle log output. All implementations of Appender must be safe for concurrent use.
type AppenderBase ¶ added in v0.0.10
type AppenderBase struct {
Name string `PluginAttribute:"name"`
}
AppenderBase provides common configuration fields for all appenders.
func (*AppenderBase) GetName ¶ added in v0.0.10
func (c *AppenderBase) GetName() string
GetName returns the appender's name.
func (*AppenderBase) ReportError ¶
func (c *AppenderBase) ReportError(err error)
ReportError reports an error to the appender.
type AppenderRef ¶
type AppenderRef struct {
Appender
Ref string `PluginAttribute:"ref"`
Level LevelRange `PluginAttribute:"level,default="`
}
AppenderRef represents a reference to an Appender by name. The actual Appender is resolved and injected during configuration.
func (*AppenderRef) Append ¶ added in v0.1.0
func (c *AppenderRef) Append(e *Event)
Append forwards the event to each child appender.
func (*AppenderRef) Write ¶
func (c *AppenderRef) Write(b []byte)
Write forwards raw bytes to each child appender.
type AppenderRefs ¶ added in v0.1.0
type AppenderRefs struct {
AppenderRefs []*AppenderRef `PluginElement:"appenderRef"`
}
AppenderRefs represents a collection of AppenderRef objects.
type ArrayValue ¶
type ArrayValue interface {
EncodeArray(enc Encoder)
}
ArrayValue is an interface for types that can be encoded as array.
type AsyncLogger ¶ added in v0.0.4
type AsyncLogger struct {
LoggerBase
AppenderRefs
BufferSize int `PluginAttribute:"bufferSize,default=10000"`
BufferFullPolicy BufferFullPolicy `PluginAttribute:"bufferFullPolicy,default=Discard"`
// contains filtered or unexported fields
}
AsyncLogger is an asynchronous logger that buffers events and processes them in a dedicated background goroutine.
func (*AsyncLogger) Append ¶ added in v0.1.0
func (c *AsyncLogger) Append(e *Event)
Append enqueues a log event into the buffer. Behavior on full buffer depends on BufferFullPolicy.
func (*AsyncLogger) ConcurrentSafe ¶
func (c *AsyncLogger) ConcurrentSafe() bool
func (*AsyncLogger) GetDiscardCounter ¶ added in v0.0.5
func (c *AsyncLogger) GetDiscardCounter() int64
GetDiscardCounter returns the total number of discarded events and data.
func (*AsyncLogger) Start ¶ added in v0.0.4
func (c *AsyncLogger) Start() error
Start initializes the AsyncLogger and launches the worker goroutine.
func (*AsyncLogger) Stop ¶ added in v0.0.4
func (c *AsyncLogger) Stop()
Stop gracefully shuts down the async logger.
func (*AsyncLogger) Write ¶ added in v0.0.4
func (c *AsyncLogger) Write(b []byte)
Write enqueues raw bytes into the buffer. Behavior on full buffer depends on BufferFullPolicy.
type BaseLayout ¶
type BaseLayout struct {
FileLineLength int `PluginAttribute:"fileLineLength,default=48"`
}
BaseLayout provides common functionality for layouts.
func (*BaseLayout) GetBuffer ¶
func (c *BaseLayout) GetBuffer() *bytes.Buffer
GetBuffer returns a buffer from the pool (or a new one if empty).
func (*BaseLayout) GetFileLine ¶
func (c *BaseLayout) GetFileLine(e *Event) string
GetFileLine returns "file:line" string for the log event. If the string is too long, it is truncated and prefixed with "...".
func (*BaseLayout) PutBuffer ¶
func (c *BaseLayout) PutBuffer(buf *bytes.Buffer)
PutBuffer resets and returns a buffer to the pool, but only if it does not exceed the configured capacity.
type BufferFullPolicy ¶ added in v0.0.5
type BufferFullPolicy int
BufferFullPolicy specifies what to do when an async buffer is full.
func ParseBufferFullPolicy ¶ added in v0.0.5
func ParseBufferFullPolicy(s string) (BufferFullPolicy, error)
ParseBufferFullPolicy converts a string to a BufferFullPolicy.
type CallerType ¶ added in v0.1.0
type CallerType int
CallerType defines the type of caller information to retrieve.
const ( // CallerTypeDefault indicates that the caller information should be retrieved // using the default method. CallerTypeDefault CallerType = iota // CallerTypeFast indicates that the caller information should be retrieved // using a faster but less accurate method. CallerTypeFast // CallerTypeNone indicates that no caller information should be retrieved. CallerTypeNone )
type ConsoleAppender ¶
type ConsoleAppender struct {
AppenderBase
Layout Layout `PluginElement:"layout,default=TextLayout"`
}
ConsoleAppender writes formatted log events to standard output.
func (*ConsoleAppender) Append ¶
func (c *ConsoleAppender) Append(e *Event)
Append formats the event and writes it to standard output.
func (*ConsoleAppender) ConcurrentSafe ¶ added in v0.1.0
func (c *ConsoleAppender) ConcurrentSafe() bool
func (*ConsoleAppender) Start ¶ added in v0.1.0
func (c *ConsoleAppender) Start() error
func (*ConsoleAppender) Stop ¶ added in v0.1.0
func (c *ConsoleAppender) Stop()
func (*ConsoleAppender) Write ¶ added in v0.0.4
func (c *ConsoleAppender) Write(b []byte)
Write writes a byte slice directly to standard output.
type ConsoleLogger ¶ added in v0.1.0
type ConsoleLogger struct {
LoggerBase
ConsoleAppender
}
ConsoleLogger writes log events to standard output.
func (*ConsoleLogger) Append ¶ added in v0.1.0
func (c *ConsoleLogger) Append(e *Event)
Append sends the event to the console if the level is enabled.
type DiscardAppender ¶
type DiscardAppender struct {
AppenderBase
}
DiscardAppender ignores all log events (no-op).
func (*DiscardAppender) Append ¶ added in v0.1.0
func (c *DiscardAppender) Append(e *Event)
func (*DiscardAppender) ConcurrentSafe ¶ added in v0.1.0
func (c *DiscardAppender) ConcurrentSafe() bool
func (*DiscardAppender) Start ¶ added in v0.1.0
func (c *DiscardAppender) Start() error
func (*DiscardAppender) Stop ¶ added in v0.1.0
func (c *DiscardAppender) Stop()
func (*DiscardAppender) Write ¶
func (c *DiscardAppender) Write(b []byte)
type DiscardLogger ¶ added in v0.1.0
type DiscardLogger struct {
LoggerBase
DiscardAppender
}
DiscardLogger ignores all log events (no-op).
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 defines the interface for structured logging encoders. Implementations control how log fields are serialized (e.g. JSON, text).
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 // String representation extracted from the context (e.g., trace ID)
CtxFields []Field // Additional structured fields extracted from the context (e.g., request ID, user ID)
}
Event represents a single log entry. It contains both the log message context (e.g., time, file, line, tag) and structured metadata (fields and context values).
type Field ¶
type Field struct {
Key string // The field key
Type ValueType // The type of the value
Num uint64 // Holds numeric values or length/bit-representation
Any any // Holds pointers, references, or arbitrary values
}
Field represents a structured log field with a key and a typed 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 FieldsFromMap ¶ added in v0.0.4
FieldsFromMap creates a special Field that wraps a map[string]any. When encoded, it expands the map into individual key-value fields. This allows existing map structures to be easily converted into log fields without manually iterating through the map and adding each field individually.
func Object ¶
Object creates a Field containing a variadic slice of Fields, treated as a nested object.
type FileAppender ¶
type FileAppender struct {
AppenderBase
Layout Layout `PluginElement:"layout,default=TextLayout"`
FileDir string `PluginAttribute:"fileDir,default=./logs"`
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.
func (*FileAppender) ConcurrentSafe ¶ added in v0.1.0
func (c *FileAppender) ConcurrentSafe() bool
func (*FileAppender) Start ¶
func (c *FileAppender) Start() error
Start opens the log file for appending.
func (*FileAppender) Write ¶ added in v0.0.4
func (c *FileAppender) Write(b []byte)
Write writes a byte slice directly to the file.
type FileLogger ¶ added in v0.1.0
type FileLogger struct {
LoggerBase
FileAppender
}
FileLogger writes log events to a file.
func (*FileLogger) Append ¶ added in v0.1.0
func (c *FileLogger) Append(e *Event)
Append writes the event to the file if the level is enabled.
type HumanizeBytes ¶
type HumanizeBytes int
HumanizeBytes represents a human-readable byte size
func ParseHumanizeBytes ¶
func ParseHumanizeBytes(s string) (HumanizeBytes, error)
ParseHumanizeBytes converts a human-readable byte string (e.g., "10KB") to an integer.
type JSONEncoder ¶
type JSONEncoder struct {
// contains filtered or unexported fields
}
JSONEncoder encodes log fields into standard JSON format.
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 to JSON and writes it. If marshalling fails, the error message is written as a string.
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 a log event as a structured JSON object.
func (*JSONLayout) ToBytes ¶
func (c *JSONLayout) ToBytes(e *Event) []byte
ToBytes converts a log event to JSON representation.
type JSONTokenType ¶ added in v0.0.10
type JSONTokenType int
JSONTokenType represents the type of the last token written to JSONEncoder. It is used to determine when separators (commas) are required.
const ( JSONTokenUnknown JSONTokenType = iota JSONTokenObjectBegin JSONTokenObjectEnd JSONTokenArrayBegin JSONTokenArrayEnd JSONTokenKey JSONTokenValue )
type Level ¶
type Level struct {
// contains filtered or unexported fields
}
Level represents a logging severity level. Each level has a numeric code (for comparison) and a string name (for display).
func RegisterLevel ¶ added in v0.0.6
RegisterLevel defines a new logging Level with the given code and name. The Level is also stored in the global levels map for string lookups. Name is normalized to uppercase for consistency.
type LevelRange ¶ added in v0.1.0
LevelRange represents a range of log levels [MinLevel, MaxLevel).
func ParseLevelRange ¶ added in v0.1.0
func ParseLevelRange(s string) (LevelRange, error)
ParseLevelRange parses a string into a LevelRange.
Supported formats:
"" → [NONE, MAX) "INFO" → [INFO, MAX) "INFO~ERROR" → [INFO, ERROR)
The comparison is case-insensitive. Returns an error for unknown levels.
func (LevelRange) Enable ¶ added in v0.1.0
func (c LevelRange) Enable(l Level) bool
Enable returns true if the given Level 'l' falls within the LevelRange. The check is inclusive of MinLevel and exclusive of MaxLevel.
type Lifecycle ¶
type Lifecycle interface {
Start() error
Stop()
}
Lifecycle is an optional interface for plugin lifecycle hooks.
type Logger ¶
type Logger interface {
Appender
GetTags() []string
GetLevel() LevelRange
}
Logger is the interface implemented by all loggers.
type LoggerBase ¶ added in v0.0.10
type LoggerBase struct {
Name string `PluginAttribute:"name"` // Logger name
Tags []string `PluginAttribute:"tags,default="` // Optional tags
Level LevelRange `PluginAttribute:"level,default="` // Logger level range
Layout Layout `PluginElement:"layout?"` // Layout for formatting logs
}
LoggerBase contains fields shared by all logger configurations.
func (*LoggerBase) GetLevel ¶ added in v0.1.0
func (c *LoggerBase) GetLevel() LevelRange
GetLevel returns the level range of the logger.
func (*LoggerBase) GetName ¶ added in v0.0.10
func (c *LoggerBase) GetName() string
GetName returns the name of the logger.
func (*LoggerBase) GetTags ¶ added in v0.1.0
func (c *LoggerBase) GetTags() []string
GetTags returns the tags of the logger.
type LoggerWrapper ¶ added in v0.0.4
type LoggerWrapper struct {
// contains filtered or unexported fields
}
LoggerWrapper wraps a Logger instance and allows atomic replacement of the underlying Logger at runtime. This ensures that concurrent readers always see a consistent Logger reference without needing locks.
func GetLogger ¶ added in v0.0.4
func GetLogger(name string) *LoggerWrapper
GetLogger retrieves an existing LoggerWrapper by name, or creates a new one if it does not exist yet.
This function must be called only during the initialization phase. It panics if called after global.init is set, indicating that the logging system has already been finalized.
type Plugin ¶
type Plugin struct {
Name string // Name of the plugin
Class reflect.Type // Underlying struct type
File string // File where plugin was registered
Line int // Line number where plugin was registered
}
Plugin represents metadata about a plugin type.
type PluginTag ¶
type PluginTag string
PluginTag is a wrapper for parsing struct field tags.
type RollingFileAppender ¶ added in v0.1.0
type RollingFileAppender struct {
AppenderBase
Layout Layout `PluginElement:"layout,default=TextLayout"`
FileDir string `PluginAttribute:"fileDir,default=./logs"`
FileName string `PluginAttribute:"fileName"`
Interval time.Duration `PluginAttribute:"interval,default=1h"`
MaxAge time.Duration `PluginAttribute:"maxAge,default=168h"`
Lock bool `PluginAttribute:"lock,default=false"`
// contains filtered or unexported fields
}
RollingFileAppender writes logs to files that rotate based on time. It is safe for multiple goroutines to call Write() concurrently only if Lock=true. If Lock=false, concurrent writes must be serialized by the caller (e.g., async logger).
func (*RollingFileAppender) Append ¶ added in v0.1.0
func (c *RollingFileAppender) Append(e *Event)
Append formats the log event and writes it to the current file.
func (*RollingFileAppender) ConcurrentSafe ¶ added in v0.1.0
func (c *RollingFileAppender) ConcurrentSafe() bool
func (*RollingFileAppender) Start ¶ added in v0.1.0
func (c *RollingFileAppender) Start() error
Start opens the initial log file and prepares for rotation.
func (*RollingFileAppender) Stop ¶ added in v0.1.0
func (c *RollingFileAppender) Stop()
Stop flushes and closes the current file.
func (*RollingFileAppender) Write ¶
func (c *RollingFileAppender) Write(b []byte)
Write writes bytes to the current log file. Lock=true ensures thread safety internally; Lock=false assumes caller serializes writes.
type RollingFileLogger ¶ added in v0.1.0
type RollingFileLogger struct {
LoggerBase
// File output configuration
FileDir string `PluginAttribute:"fileDir,default=./logs"`
FileName string `PluginAttribute:"fileName,default=app.log"`
// If true, warning/error logs go to a separate .wf file.
Separate bool `PluginAttribute:"separate,default=false"`
// Rotation and retention
Interval time.Duration `PluginAttribute:"interval,default=1h"`
MaxAge time.Duration `PluginAttribute:"maxAge,default=168h"`
// Async logging options
AsyncWrite bool `PluginAttribute:"async,default=false"`
BufferSize int `PluginAttribute:"bufferSize,default=10000"`
BufferFullPolicy BufferFullPolicy `PluginAttribute:"bufferFullPolicy,default=Discard"`
// contains filtered or unexported fields
}
RollingFileLogger writes log events to files with optional rotation, separation, and async behavior.
func (*RollingFileLogger) Append ¶ added in v0.1.0
func (f *RollingFileLogger) Append(e *Event)
Append forwards the event to the underlying logger.
func (*RollingFileLogger) ConcurrentSafe ¶
func (f *RollingFileLogger) ConcurrentSafe() bool
func (*RollingFileLogger) Start ¶ added in v0.1.0
func (f *RollingFileLogger) Start() error
Start initializes the RollingFileLogger, either synchronous or asynchronous.
func (*RollingFileLogger) Stop ¶ added in v0.1.0
func (f *RollingFileLogger) Stop()
Stop stops all appenders.
func (*RollingFileLogger) Write ¶
func (f *RollingFileLogger) Write(b []byte)
Write forwards raw bytes to the underlying logger.
type RollingFileWriter ¶ added in v0.1.0
type RollingFileWriter struct {
// contains filtered or unexported fields
}
RollingFileWriter is the low-level sequential writer. It is NOT safe for concurrent use; synchronization is the responsibility of the caller/appender.
func (*RollingFileWriter) Close ¶ added in v0.1.0
func (w *RollingFileWriter) Close()
Close closes the current file.
type SyncLogger ¶ added in v0.0.4
type SyncLogger struct {
LoggerBase
AppenderRefs
}
SyncLogger is a synchronous logger that immediately forwards events to appenders.
func (*SyncLogger) Append ¶ added in v0.1.0
func (c *SyncLogger) Append(e *Event)
Append sends the event directly to appenders (blocking).
func (*SyncLogger) ConcurrentSafe ¶
func (c *SyncLogger) ConcurrentSafe() bool
func (*SyncLogger) Start ¶ added in v0.0.4
func (c *SyncLogger) Start() error
func (*SyncLogger) Stop ¶ added in v0.0.4
func (c *SyncLogger) Stop()
func (*SyncLogger) Write ¶ added in v0.0.4
func (c *SyncLogger) Write(b []byte)
Write writes raw bytes directly to appenders.
type Tag ¶
type Tag struct {
// contains filtered or unexported fields
}
Tag represents a named log tag, used to categorize logs by subsystem, business domain, or RPC interaction, and so on. Each Tag holds a reference to a Logger.
func RegisterAppTag ¶ added in v0.0.4
RegisterAppTag registers or retrieves a Tag intended for application-layer logs.
- subType: component or module name
- action: lifecycle phase or behavior (optional)
func RegisterBizTag ¶ added in v0.0.4
RegisterBizTag registers or retrieves a Tag intended for business-logic logs.
- subType: business domain or feature name
- action: operation being logged (optional)
func RegisterRPCTag ¶ added in v0.0.4
RegisterRPCTag registers or retrieves a Tag intended for RPC logs, covering external/internal dependency interactions.
- subType: protocol or target system (e.g., http, grpc, redis)
- action: RPC phase (e.g., send, retry, fail)
func RegisterTag ¶ added in v0.0.4
RegisterTag retrieves or creates a Tag by name. If the tag is not yet registered, it is associated with initLogger. Panics if called after global.init is set (i.e., after logging refresh).
Normally, higher-level helpers like RegisterAppTag, RegisterBizTag, or RegisterRPCTag should be used to ensure semantic consistency.
type TextEncoder ¶
type TextEncoder struct {
// contains filtered or unexported fields
}
TextEncoder encodes fields as "key=value" pairs separated by a delimiter. Nested arrays/objects are serialized as JSON using an internal JSONEncoder.
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 a log event as a human-readable text line.
func (*TextLayout) ToBytes ¶
func (c *TextLayout) ToBytes(e *Event) []byte
ToBytes converts a log event into a plain-text line with separators.