lx

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 6 Imported by: 2

Documentation

Index

Constants

View Source
const (
	Space        = " "  // Single space for separating elements (e.g., between level and message)
	DoubleSpace  = "  " // Double space for indentation (e.g., for hierarchical output)
	Slash        = "/"  // Separator for namespace paths (e.g., "parent/child")
	Arrow        = "→"  // Arrow for NestedPath style namespaces (e.g., [parent]→[child])
	LeftBracket  = "["  // Opening bracket for namespaces and fields (e.g., [app])
	RightBracket = "]"  // Closing bracket for namespaces and fields (e.g., [app])
	Colon        = ":"  // Separator after namespace or level (e.g., [app]: INFO:) can also be "|"
	Dot          = "."  // Separator for namespace paths (e.g., "parent.child")
	Newline      = "\n" // Newline for separating log entries or stack trace lines
)

Formatting constants for log output. These constants define the characters used to format log messages, ensuring consistency across handlers (e.g., text, JSON, colorized). They are used to construct namespace paths, level indicators, and field separators in log entries.

View Source
const (
	DefaultEnabled = true // Default state for new loggers (disabled)
	True           = true
	False          = false
	Active         = 1
	Inactive       = -1
	Unknown        = 0
)

DefaultEnabled defines the default logging state (disabled). It specifies whether logging is enabled by default for new Logger instances in the ll package. Set to false to prevent logging until explicitly enabled.

View Source
const (
	DebugString   = "DEBUG"
	InfoString    = "INFO"
	WarnString    = "WARN"
	WarningString = "WARNING"
	ErrorString   = "ERROR"
	FatalString   = "FATAL"
	NoneString    = "NONE"
	UnknownString = "UNKNOWN"

	TextString    = "TEXT"
	JSONString    = "JSON"
	DumpString    = "DUMP"
	SpecialString = "SPECIAL"
	RawString     = "RAW"
	InspectString = "INSPECT"
	DbgString     = "DBG"
	TimedString   = "TIMED"
	StackString   = "STACK"
	OutputString  = "OUTPUT"
)

String constants for each level

Variables

This section is empty.

Functions

This section is empty.

Types

type ClassType

type ClassType int

ClassType represents the type of a log entry. It is an integer type used to categorize log entries (Text, JSON, Dump, Special, Raw), influencing how handlers process and format them.

const (
	ClassText    ClassType = iota // Text entries for standard log messages
	ClassJSON                     // JSON entries for structured output
	ClassDump                     // Dump entries for hex/ASCII dumps
	ClassSpecial                  // Special entries for custom or non-standard logs
	ClassRaw                      // Raw entries for unformatted output
	ClassInspect                  // Inspect entries for debugging
	ClassDbg                      // Inspect entries for debugging
	ClassTimed                    // Inspect entries for debugging
	ClassStack                    // Inspect entries for debugging
	ClassOutput                   // Inspect entries for debugging
	ClassUnknown                  // Unknown output
)

Log class constants, defining the type of log entry. These constants categorize log entries by their content or purpose, influencing how handlers process them (e.g., text, JSON, hex dump).

func ParseClass added in v0.1.0

func ParseClass(s string) ClassType

ParseClass converts a string to its corresponding ClassType. It parses a string (case-insensitive) and returns the corresponding ClassType, defaulting to ClassUnknown for unrecognized strings.

func (ClassType) String

func (t ClassType) String() string

String converts a ClassType to its string representation. It maps each class constant to a human-readable string, returning "UNKNOWN" for invalid classes. Used by handlers to indicate the entry type in output (e.g., JSON fields). Example:

var class lx.ClassType = lx.ClassText
fmt.Println(class.String()) // Output: TEST

type Deduper added in v0.1.7

type Deduper interface {
	Calculate(*Entry) uint64
}

Deduper defines how to calculate a deduplication key for an entry.

type Entry

type Entry struct {
	Timestamp time.Time // Time the log was created
	Level     LevelType // Severity level of the log (Debug, Info, Warn, Error, None)
	Message   string    // Log message content
	Namespace string    // Namespace path (e.g., "parent/child")
	Fields    Fields    // Additional key-value metadata (e.g., {"user": "alice"})
	Style     StyleType // Namespace formatting style (FlatPath or NestedPath)
	Error     error     // Associated error, if any (e.g., for error logs)
	Class     ClassType // Type of log entry (Text, JSON, Dump, Special, Raw)
	Stack     []byte    // Stack trace data (if present)
	Id        int       `json:"-"` // Unique ID for the entry, ignored in JSON output
}

Entry represents a single log entry passed to handlers. It encapsulates all information about a log message, including its timestamp, severity, content, namespace, metadata, and formatting style. Handlers process Entry instances to produce formatted output (e.g., text, JSON). The struct is immutable once created, ensuring thread-safety in handler processing.

type Field added in v0.1.5

type Field struct {
	Key   string
	Value interface{}
}

Field represents a key-value pair where the key is a string and the value is of any type.

type Fields added in v0.1.5

type Fields []Field

Fields represents a slice of key-value pairs.

func (Fields) Filter added in v0.1.5

func (f Fields) Filter(predicate func(key string, value interface{}) bool) Fields

Filter returns a new Fields slice containing only pairs where the predicate returns true. Example:

fields := lx.Fields{{"user", "alice"}, {"password", "secret"}, {"age", 30}}
filtered := fields.Filter(func(key string, value interface{}) bool {
    return key != "password" // Remove sensitive fields
})

func (Fields) Get added in v0.1.5

func (f Fields) Get(key string) (interface{}, bool)

Get returns the value for a given key and a boolean indicating if the key was found. This provides O(n) lookup, which is fine for small numbers of fields. Example:

fields := lx.Fields{{"user", "alice"}, {"age", 30}}
value, found := fields.Get("user") // Returns "alice", true

func (Fields) Map added in v0.1.5

func (f Fields) Map() map[string]interface{}

Map converts the Fields slice to a map[string]interface{}. This is useful for backward compatibility or when map operations are needed. Example:

fields := lx.Fields{{"user", "alice"}, {"age", 30}}
m := fields.Map() // Returns map[string]interface{}{"user": "alice", "age": 30}

func (Fields) Merge added in v0.1.5

func (f Fields) Merge(other Fields) Fields

Merge merges another Fields slice into this one, with the other slice's fields taking precedence for duplicate keys (overwrites existing keys). Example:

base := lx.Fields{{"user", "alice"}, {"age", 30}}
additional := lx.Fields{{"age", 31}, {"city", "NYC"}}
merged := base.Merge(additional)
// Returns: {{"user", "alice"}, {"age", 31}, {"city", "NYC"}}

func (Fields) String added in v0.1.5

func (f Fields) String() string

String returns a human-readable string representation of the fields. Example:

fields := lx.Fields{{"user", "alice"}, {"age", 30}}
str := fields.String() // Returns: "[user=alice age=30]"

func (Fields) Translate added in v0.1.5

func (f Fields) Translate(mapping map[string]string) Fields

Translate returns a new Fields slice with keys translated according to the provided mapping. Keys not in the mapping are passed through unchanged. This is useful for adapters like Victoria. Example:

fields := lx.Fields{{"user", "alice"}, {"timestamp", time.Now()}}
translated := fields.Translate(map[string]string{
    "user": "username",
    "timestamp": "ts",
})
// Returns: {{"username", "alice"}, {"ts", time.Now()}}

type Handler

type Handler interface {
	Handle(e *Entry) error // Processes a log entry, returning any error
}

Handler defines the interface for processing log entries. Implementations (e.g., TextHandler, JSONHandler) format and output log entries to various destinations (e.g., stdout, files). The Handle method returns an error if processing fails, allowing the logger to handle output failures gracefully. Example (simplified handler implementation):

type MyHandler struct{}
func (h *MyHandler) Handle(e *Entry) error {
    fmt.Printf("[%s] %s: %s\n", e.Namespace, e.Level.String(), e.Message)
    return nil
}

type HandlerOutputter added in v0.1.5

type HandlerOutputter interface {
	Handler   // Can process log entries
	Outputter // Can change output destination (has Output(w io.Writer) method)
}

HandlerOutputter combines the Handler and Outputter interfaces. Types implementing this interface can both process log entries and dynamically change their output destination at runtime.

This is useful for creating flexible logging handlers that support features like log rotation, output redirection, or runtime configuration.

Example usage:

var ho HandlerOutputter = &TextHandler{}
// Handle log entries
ho.Handle(&Entry{...})
// Switch output destination
ho.Output(os.Stderr)

Common implementations include TextHandler and JSONHandler when they support output destination changes.

type LevelType

type LevelType int

LevelType represents the severity of a log message. It is an integer type used to define log levels (Debug, Info, Warn, Error, None), with associated string representations for display in log output.

const (
	LevelNone    LevelType = iota // Debug level for detailed diagnostic information
	LevelInfo                     // Info level for general operational messages
	LevelWarn                     // Warn level for warning conditions
	LevelError                    // Error level for error conditions requiring attention
	LevelFatal                    // Fatal level for critical error conditions
	LevelDebug                    // None level for logs without a specific severity (e.g., raw output)
	LevelUnknown                  // None level for logs without a specific severity (e.g., raw output)
)

Log level constants, ordered by increasing severity. These constants define the severity levels for log messages, used to filter logs based on the logger’s minimum level. They are ordered to allow comparison (e.g., LevelDebug < LevelWarn).

func LevelParse added in v0.1.0

func LevelParse(s string) LevelType

LevelParse converts a string to its corresponding LevelType. It parses a string (case-insensitive) and returns the corresponding LevelType, defaulting to LevelUnknown for unrecognized strings. Supports "WARNING" as an alias for "WARN".

func (LevelType) Name added in v0.1.5

func (l LevelType) Name(class ClassType) string

func (LevelType) String

func (l LevelType) String() string

String converts a LevelType to its string representation. It maps each level constant to a human-readable string, returning "UNKNOWN" for invalid levels. Used by handlers to display the log level in output. Example:

var level lx.LevelType = lx.LevelInfo
fmt.Println(level.String()) // Output: INFO

type Namespace

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

Namespace manages thread-safe namespace enable/disable states with caching. The store holds explicit user-defined rules (path -> bool). The cache holds computed effective states for paths (path -> namespaceRule) based on hierarchical rules to optimize lookups.

func (*Namespace) Enabled

func (ns *Namespace) Enabled(path string, separator string) (isEnabledByRule bool, isDisabledByRule bool)

Enabled checks if a path is enabled by namespace rules, considering the most specific rule (path or closest prefix) in the store. Results are cached. Args:

  • path: Absolute namespace path to check.
  • separator: Character delimiting path segments (e.g., "/", ".").

Returns:

  • isEnabledByRule: True if an explicit rule enables the path.
  • isDisabledByRule: True if an explicit rule disables the path.

If both are false, no explicit rule applies to the path or its prefixes.

func (*Namespace) Set

func (ns *Namespace) Set(path string, enabled bool)

Set defines an explicit enable/disable rule for a namespace path. It clears the cache to ensure subsequent lookups reflect the change.

func (*Namespace) Store

func (ns *Namespace) Store(path string, rule bool)

Store directly sets a rule in the store, bypassing cache invalidation. Intended for internal use or sync.Map parity; prefer Set for standard use.

type Outputter added in v0.1.5

type Outputter interface {
	Output(w io.Writer)
}

Outputter defines the interface for handlers that support dynamic output destination changes. Implementations can switch their output writer at runtime.

Example usage:

h := &JSONHandler{}
h.Output(os.Stderr) // Switch to stderr
h.Output(file)      // Switch to file

type StyleType

type StyleType int

StyleType defines how namespace paths are formatted in log output. It is an integer type used to select between FlatPath (parent/child) and NestedPath ([parent]→[child]) styles, affecting how handlers render namespace hierarchies.

const (
	FlatPath   StyleType = iota // Formats namespaces as [parent/child]
	NestedPath                  // Formats namespaces as [parent]→[child]
)

Namespace style constants. These constants define how namespace paths are formatted in log output, affecting the visual representation of hierarchical namespaces.

type Timestamper added in v0.0.9

type Timestamper interface {
	// Timestamped enables or disables timestamp logging and allows specifying an optional format.
	// Parameters:
	//   enable: Boolean to enable or disable timestamp logging
	//   format: Optional string(s) to specify the timestamp format
	Timestamped(enable bool, format ...string)
}

Timestamper defines an interface for handlers that support timestamp configuration. It includes a method to enable or disable timestamp logging and optionally set the timestamp format.

type Wrap added in v0.1.5

type Wrap func(next Handler) Handler

Wrap is a handler decorator function that transforms a log handler. It takes an existing handler as input and returns a new, wrapped handler that adds functionality (like filtering, transformation, or routing).

Jump to

Keyboard shortcuts

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