log

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2025 License: Apache-2.0 Imports: 23 Imported by: 43

README

Go-Spring :: Log

English | 中文

Go-Spring :: 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.

Features

  • Multi-Level Logging: Supports standard log levels such as Trace, Debug, Info, Warn, Error, Panic, and Fatal, suitable for debugging and monitoring in various scenarios.
  • Structured Logging: Records logs in a structured format with key fields like trace_id and span_id, making them easy to parse and analyze by log aggregation systems.
  • Context Integration: Extracts additional information from context.Context (e.g., request ID, user ID) and automatically attaches them to log entries.
  • Tag-Based Logging: Introduces a tag system to distinguish logs across different modules or business lines.
  • Plugin Architecture:
    • Appender: Supports multiple output targets including console and file.
    • Layout: Provides both plain text and JSON formatting for log output.
    • Logger: Offers both synchronous and asynchronous loggers; asynchronous mode avoids blocking the main thread.
  • Performance Optimizations: Utilizes buffer management and event pooling to minimize memory allocation overhead.
  • Dynamic Configuration Reload: Supports runtime reloading of logging configurations from external files.
  • Well-Tested: All core modules are covered with unit tests to ensure stability and reliability.

Installation

go get github.com/go-spring/log

Quick Start

Here's a simple example demonstrating how to use Go-Spring :: Log:

package main

import (
	"context"

	"github.com/go-spring/log"
)

func main() {
	// Set a function to extract fields from context
	log.FieldsFromContext = func(ctx context.Context) []log.Field {
		return []log.Field{
			log.String("trace_id", "0a882193682db71edd48044db54cae88"),
			log.String("span_id", "50ef0724418c0a66"),
		}
	}

	// Load configuration file
	err := log.RefreshFile("log.xml")
	if err != nil {
		panic(err)
	}

	ctx := context.Background()

	// Write logs
	log.Infof(ctx, log.TagDef, "This is an info message")
	log.Errorf(ctx, log.TagBiz, "This is an error message")
}

Configuration

Go-Spring :: Log supports XML-based configuration for full control over logging behavior:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Properties>
        <Property name="LayoutBufferSize">100KB</Property>
    </Properties>
    <Appenders>
        <Console name="console">
            <JSONLayout bufferSize="${LayoutBufferSize}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="warn">
            <AppenderRef ref="console"/>
        </Root>
        <Logger name="logger" level="info" tags="_com_request_*">
            <AppenderRef ref="console"/>
        </Logger>
    </Loggers>
</Configuration>

Plugin Development

Go-Spring :: Log offers rich plugin interfaces for developers to easily implement custom Appender, Layout, and Logger components.

License

Go-Spring :: Log is licensed under the Apache License 2.0.

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., XML 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

View Source
const (
	ValueTypeBool = ValueType(iota)
	ValueTypeInt64
	ValueTypeUint64
	ValueTypeFloat64
	ValueTypeString
	ValueTypeReflect
	ValueTypeArray
	ValueTypeObject
	ValueTypeFromMap
)
View Source
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
)
View Source
const MsgKey = "msg"

Variables

View Source
var (
	// TagAppDef is the default tag used for application logs.
	TagAppDef = RegisterAppTag("def", "")

	// TagBizDef is the default tag used for business-related logs.
	TagBizDef = RegisterBizTag("def", "")
)
View Source
var (
	// TimeNow is a function that can be overridden to provide custom
	// timestamp behavior, e.g., for testing or mocking.
	TimeNow func(ctx context.Context) time.Time

	// StringFromContext allows extraction of a string (e.g., trace ID) from the context.
	StringFromContext func(ctx context.Context) string

	// FieldsFromContext allows extraction of structured fields (e.g., trace ID, span ID) from the context.
	FieldsFromContext func(ctx context.Context) []Field
)
View Source
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.

View Source
var Stdout io.Writer = os.Stdout

Stdout is the standard output stream used by appenders.

Functions

func BuildTag added in v0.0.4

func BuildTag(mainType, subType, action string) string

BuildTag constructs a structured tag string based on main type, sub type, and action. The format is: _<mainType>_<subType> or _<mainType>_<subType>_<action>.

func Debug

func Debug(ctx context.Context, tag *Tag, fn func() []Field)

Debug logs a message at DebugLevel using a tag and a lazy field-generating function.

func Debugf

func Debugf(ctx context.Context, tag *Tag, format string, args ...any)

Debugf logs a message at DebugLevel using a tag and a formatted message.

func Destroy added in v0.0.5

func Destroy()

Destroy destroys all loggers.

func DumpNode

func DumpNode(node *Node, indent int, buf *bytes.Buffer)

DumpNode prints the structure of a Node to a buffer.

func Error

func Error(ctx context.Context, tag *Tag, fields ...Field)

Error logs a message at ErrorLevel using structured fields.

func Errorf

func Errorf(ctx context.Context, tag *Tag, format string, args ...any)

Errorf logs a message at ErrorLevel using a formatted message.

func Fatal

func Fatal(ctx context.Context, tag *Tag, fields ...Field)

Fatal logs a message at FatalLevel using structured fields.

func Fatalf

func Fatalf(ctx context.Context, tag *Tag, format string, args ...any)

Fatalf logs a message at FatalLevel using a formatted message.

func GetAllTags

func GetAllTags() []string

GetAllTags returns all registered tags.

func Info

func Info(ctx context.Context, tag *Tag, fields ...Field)

Info logs a message at InfoLevel using structured fields.

func Infof

func Infof(ctx context.Context, tag *Tag, format string, args ...any)

Infof logs a message at InfoLevel using a formatted message.

func MapKeys

func MapKeys[M ~map[K]V, K comparable, V any](m M) []K

MapKeys returns the keys of the map m.

func NewPlugin

func NewPlugin(t reflect.Type, node *Node, properties map[string]string) (reflect.Value, error)

NewPlugin Creates and initializes a plugin instance.

func OrderedMapKeys

func OrderedMapKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K

OrderedMapKeys returns the keys of the map m in sorted order.

func Panic

func Panic(ctx context.Context, tag *Tag, fields ...Field)

Panic logs a message at PanicLevel using structured fields.

func Panicf

func Panicf(ctx context.Context, tag *Tag, format string, args ...any)

Panicf logs a message at PanicLevel using a formatted message.

func Ptr

func Ptr[T any](i T) *T

Ptr returns a pointer to the given value.

func PutEvent

func PutEvent(e *Event)

PutEvent resets the given Event and returns it to the pool for reuse.

func Record

func Record(ctx context.Context, level Level, tag *Tag, skip int, fields ...Field)

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

func RefreshFile(fileName string) error

RefreshFile loads a logging configuration from a file by its name.

func RefreshReader

func RefreshReader(input io.Reader, ext string) error

RefreshReader reads the configuration from an io.Reader using the reader for the given extension.

func RegisterConverter

func RegisterConverter[T any](fn Converter[T])

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 RegisterProperty added in v0.0.5

func RegisterProperty(key string, val func(string) error)

RegisterProperty Registers a property with a given key.

func RegisterReader

func RegisterReader(r Reader, ext ...string)

RegisterReader registers a Reader for one or more file extensions. This allows dynamic selection of parsers based on file type.

func Trace

func Trace(ctx context.Context, tag *Tag, fn func() []Field)

Trace logs a message at TraceLevel using a tag and a lazy field-generating function.

func Tracef

func Tracef(ctx context.Context, tag *Tag, format string, args ...any)

Tracef logs a message at TraceLevel using a tag and a formatted message.

func Warn

func Warn(ctx context.Context, tag *Tag, fields ...Field)

Warn logs a message at WarnLevel using structured fields.

func Warnf

func Warnf(ctx context.Context, tag *Tag, format string, args ...any)

Warnf logs a message at WarnLevel using a formatted message.

func WrapError

func WrapError(err error, format string, args ...any) error

WrapError wraps an existing error, creating a new error with hierarchical relationships.

func WriteFields

func WriteFields(enc Encoder, fields []Field)

WriteFields writes a slice of Field objects to the encoder.

func WriteLogString

func WriteLogString(buf *bytes.Buffer, s string)

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
	Write(b []byte)  // Directly writes a bytes slice
}

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 AsyncLogger added in v0.0.4

type AsyncLogger struct {
	BaseLogger
	BufferSize       int              `PluginAttribute:"bufferSize,default=10000"`
	BufferFullPolicy BufferFullPolicy `PluginAttribute:"bufferFullPolicy,default=Discard"`
	// contains filtered or unexported fields
}

AsyncLogger is an asynchronous logger configuration. It buffers log events and processes them in a separate goroutine.

func (*AsyncLogger) GetDiscardCounter added in v0.0.5

func (c *AsyncLogger) GetDiscardCounter() int64

GetDiscardCounter returns the count of discarded events.

func (*AsyncLogger) Publish added in v0.0.4

func (c *AsyncLogger) Publish(e *Event)

Publish places the event in the buffer if there's space; drops it otherwise.

func (*AsyncLogger) Start added in v0.0.4

func (c *AsyncLogger) Start() error

Start initializes the asynchronous logger and starts its worker goroutine.

func (*AsyncLogger) Stop added in v0.0.4

func (c *AsyncLogger) Stop()

Stop shuts down the asynchronous logger and waits for the worker goroutine to finish.

func (*AsyncLogger) Write added in v0.0.4

func (c *AsyncLogger) Write(b []byte)

Write writes the raw bytes directly to the appenders.

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

func (*BaseAppender) Write added in v0.0.4

func (c *BaseAppender) Write(b []byte)

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 BaseLogger added in v0.0.4

type BaseLogger struct {
	Name         string         `PluginAttribute:"name"`
	Level        Level          `PluginAttribute:"level"`
	Tags         string         `PluginAttribute:"tags,default="`
	AppenderRefs []*AppenderRef `PluginElement:"AppenderRef"`
}

BaseLogger contains shared fields for all logger configurations.

func (*BaseLogger) EnableLevel added in v0.0.4

func (c *BaseLogger) EnableLevel(level Level) bool

EnableLevel returns true if the specified log level is enabled.

func (*BaseLogger) GetName added in v0.0.4

func (c *BaseLogger) GetName() string

GetName returns the name of the logger.

type BufferFullPolicy added in v0.0.5

type BufferFullPolicy int

BufferFullPolicy specifies the behavior when the buffer is full.

func ParseBufferFullPolicy added in v0.0.5

func ParseBufferFullPolicy(s string) (BufferFullPolicy, error)

ParseBufferFullPolicy converts a string to a BufferFullPolicy.

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.

func (*ConsoleAppender) Write added in v0.0.4

func (c *ConsoleAppender) Write(b []byte)

Write writes a bytes slice directly to the stdout.

type Converter

type Converter[T any] func(string) (T, error)

Converter function type that converts string to a specific type T.

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.

func GetEvent

func GetEvent() *Event

GetEvent retrieves an *Event from the pool. If the pool is empty, a new Event will be created by the New function.

func (*Event) Reset

func (e *Event) Reset()

Reset clears the Event's fields so the instance can be reused.

type Field

type Field struct {
	Key  string
	Type ValueType
	Num  uint64
	Any  any
}

Field represents a structured log field with a key and a value.

func Any

func Any(key string, value any) Field

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 Bool

func Bool(key string, val bool) Field

Bool creates a Field for a boolean value.

func BoolPtr

func BoolPtr(key string, val *bool) Field

BoolPtr creates a Field from a *bool, or a nil Field if the pointer is nil.

func Bools

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

Bools creates a Field with a slice of booleans.

func FieldsFromMap added in v0.0.4

func FieldsFromMap(m map[string]any) Field

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 Float

func Float[T FloatType](key string, val T) Field

Float creates a Field for a float32 value.

func FloatPtr

func FloatPtr[T FloatType](key string, val *T) Field

FloatPtr creates a Field from a *float32, or returns Nil if pointer is nil.

func Floats

func Floats[T FloatType](key string, val []T) Field

Floats creates a Field with a slice of float32 values.

func Int

func Int[T IntType](key string, val T) Field

Int creates a Field for an int value.

func IntPtr

func IntPtr[T IntType](key string, val *T) Field

IntPtr creates a Field from a *int, or returns Nil if pointer is nil.

func Ints

func Ints[T IntType](key string, val []T) Field

Ints creates a Field with a slice of integers.

func Msg

func Msg(msg string) Field

Msg creates a string Field with the "msg" key.

func Msgf

func Msgf(format string, args ...any) Field

Msgf formats a message using fmt.Sprintf and creates a string Field with "msg" key.

func Nil

func Nil(key string) Field

Nil creates a Field with a nil value.

func Object

func Object(key string, fields ...Field) Field

Object creates a Field containing a variadic slice of Fields, treated as a nested object.

func Reflect

func Reflect(key string, val any) Field

Reflect wraps any value into a Field using reflection.

func String

func String(key string, val string) Field

String creates a Field for a string value.

func StringPtr

func StringPtr(key string, val *string) Field

StringPtr creates a Field from a *string, or returns Nil if pointer is nil.

func Strings

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

Strings creates a Field with a slice of strings.

func Uint

func Uint[T UintType](key string, val T) Field

Uint creates a Field for an uint value.

func UintPtr

func UintPtr[T UintType](key string, val *T) Field

UintPtr creates a Field from a *uint, or returns Nil if pointer is nil.

func Uints

func Uints[T UintType](key string, val []T) Field

Uints creates a Field with a slice of unsigned integers.

func (Field) Encode

func (f Field) Encode(enc Encoder)

Encode encodes the Field into the Encoder based on its type.

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.

func (*FileAppender) Start

func (c *FileAppender) Start() error

Start opens the file.

func (*FileAppender) Stop

func (c *FileAppender) Stop()

Stop closes the file.

func (*FileAppender) Write added in v0.0.4

func (c *FileAppender) Write(b []byte)

Write writes a bytes slice directly to the file.

type FloatType

type FloatType interface {
	~float32 | ~float64
}

FloatType is the type of float32, float64.

type HumanizeBytes

type HumanizeBytes int

func ParseHumanizeBytes

func ParseHumanizeBytes(s string) (HumanizeBytes, error)

ParseHumanizeBytes converts a human-readable byte string to an integer.

type IntType

type IntType interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

IntType is the type of int, int8, int16, int32, int64.

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.

func (*JSONEncoder) Reset

func (enc *JSONEncoder) Reset()

Reset resets the encoder's state.

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 Layout

type Layout interface {
	ToBytes(e *Event) []byte
}

Layout is the interface that defines how a log event is converted to bytes.

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

func ParseLevel(s string) (Level, error)

ParseLevel converts a string (case-insensitive) into a corresponding Level value. Returns an error if the input string does not match any valid level.

func (Level) String

func (l Level) String() string

type Lifecycle

type Lifecycle interface {
	Start() error
	Stop()
}

Lifecycle Optional lifecycle interface for plugin instances.

type Logger

type Logger interface {
	Lifecycle                     // Start/Stop methods
	GetName() string              // Get the name of the logger
	Publish(e *Event)             // Logic for sending events to appenders
	Write(b []byte)               // Direct write of raw bytes to appenders
	EnableLevel(level Level) bool // Whether a log level is enabled
}

Logger is the interface implemented by all logger configs.

type LoggerHolder added in v0.0.5

type LoggerHolder struct {
	Logger
}

LoggerHolder is a wrapper struct used to store a Logger in an atomic.Value, ensuring type consistency and safe concurrent access.

type LoggerWrapper added in v0.0.4

type LoggerWrapper struct {
	// contains filtered or unexported fields
}

LoggerWrapper wraps a Logger instance, allowing atomic replacement of the logger.

func GetLogger added in v0.0.4

func GetLogger(name string) *LoggerWrapper

GetLogger retrieves an existing LoggerWrapper by name or creates a new one. It panics if the global initialization phase has completed.

func GetRootLogger added in v0.0.5

func GetRootLogger() *LoggerWrapper

GetRootLogger retrieves the root LoggerWrapper.

func (*LoggerWrapper) Write added in v0.0.4

func (m *LoggerWrapper) Write(b []byte)

Write passes the byte slice to the currently set logger's Write method.

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

func (PluginTag) Get

func (tag PluginTag) Get(key string) string

Get Gets the value of a key or the first unnamed value.

func (PluginTag) Lookup

func (tag PluginTag) Lookup(key string) (value string, ok bool)

Lookup Looks up a key-value pair in the tag.

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 Reader

type Reader interface {
	Read(b []byte) (*Node, error)
}

Reader is an interface for reading and parsing data into a Node structure.

type SyncLogger added in v0.0.4

type SyncLogger struct {
	BaseLogger
}

SyncLogger is a synchronous logger configuration.

func (*SyncLogger) Publish added in v0.0.4

func (c *SyncLogger) Publish(e *Event)

Publish sends the event directly to the appenders.

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 the raw bytes directly to the appenders.

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 RegisterAppTag added in v0.0.4

func RegisterAppTag(subType, action string) *Tag

RegisterAppTag returns a Tag used for application-layer logs (e.g., framework events, lifecycle). subType represents the component or module, action represents the lifecycle phase or behavior.

func RegisterBizTag added in v0.0.4

func RegisterBizTag(subType, action string) *Tag

RegisterBizTag returns a Tag used for business-logic logs (e.g., use cases, domain events). subType is the business domain or feature name, action is the operation being logged.

func RegisterRPCTag added in v0.0.4

func RegisterRPCTag(subType, action string) *Tag

RegisterRPCTag returns a Tag used for RPC or external/internal dependency logs. subType is the protocol or target system, action is the RPC phase (e.g., sent, retry, fail).

func RegisterTag added in v0.0.4

func RegisterTag(tag string) *Tag

RegisterTag creates or retrieves a Tag by name. If the tag does not exist in the global registry, it is created and associated with a default logger. Normally, you should use GetAppTag, GetBizTag, or GetRPCTag to create tags semantically.

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.

type UintType

type UintType interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

UintType is the type of uint, uint8, uint16, uint32, uint64.

type ValueType

type ValueType int

ValueType represents the type of value stored in a Field.

type XMLReader

type XMLReader struct{}

XMLReader is an implementation of the Reader interface that parses XML data.

func (*XMLReader) Read

func (r *XMLReader) Read(b []byte) (*Node, error)

Read parses XML bytes into a tree of Nodes. It uses a stack to track the current position in the XML hierarchy.

Jump to

Keyboard shortcuts

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