log

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

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

View Source
const (
	ValueTypeBool = ValueType(iota)
	ValueTypeInt64
	ValueTypeUint64
	ValueTypeFloat64
	ValueTypeString
	ValueTypeReflect
	ValueTypeArray
	ValueTypeObject
)
View Source
const MsgKey = "msg"

Variables

View Source
var (
	TagDef = GetTag("_def") // used when the classification of the log is unknown.
	TagApp = GetTag("_app") // used when representing the logs of the application.
)
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 FieldsFromContext func(ctx context.Context) []Field

FieldsFromContext can be set to extract structured fields from the context (e.g., trace IDs, user IDs).

View Source
var OnDropEvent func(logger string, e *Event)

OnDropEvent is a callback function that is called when an event is dropped.

View Source
var Stdout io.Writer = os.Stdout

Stdout is the standard output stream used by appenders.

View Source
var StringFromContext func(ctx context.Context) string

StringFromContext can be set to extract a string from the context.

View Source
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 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 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 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
}

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

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

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 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 Fields

func Fields(fields map[string]any) []Field

Fields converts a map of string keys to any values to a slice of Field.

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.

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

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

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

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

func GetTag(tag string) *Tag

GetTag creates or retrieves a Tag by name. If the tag does not exist, it is created and added to the global registry.

func (*Tag) GetLogger

func (m *Tag) GetLogger() *Logger

GetLogger returns the Logger associated with this tag. It uses atomic loading to ensure safe concurrent access.

func (*Tag) GetName

func (m *Tag) GetName() string

GetName returns the name of the tag.

func (*Tag) SetLogger

func (m *Tag) SetLogger(logger *Logger)

SetLogger sets or replaces the Logger associated with this tag. Uses atomic storing to ensure thread safety.

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