dl

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: MIT Imports: 11 Imported by: 78

README

dl - Dynamic Logging

Intelligent channel-based logging built on Go's slog

The dl package provides structured logging with channel-based routing, allowing different log categories to have independent destinations, formats, and configurations.

Quick Start

import "github.com/michaelquigley/df/dl"

// Basic logging
dl.Log().Info("application started")
dl.Log().With("user", "alice").Info("user logged in")

// Channel-based logging
dl.ChannelLog("database").With("table", "users").Info("query executed")
dl.ChannelLog("http").With("status", 200).Info("request processed")

Key Features

  • 📡 Channel Routing: Route logs to different destinations by category
  • ⚙️ Per-Channel Config: Independent format, level, and output per channel
  • 🎨 Multiple Formats: Pretty console output or structured JSON
  • 🔗 Builder Pattern: Fluent API with .With() for contextual attributes
  • 🎯 Smart Defaults: Works immediately, configure only what you need
  • 🔄 Thread-Safe: Concurrent logging across all channels

Core Functions

  • dl.Log() - Default logger builder
  • dl.ChannelLog(name) - Channel-specific logger builder
  • dl.ConfigureChannel(name, opts) - Configure channel behavior
  • dl.DefaultOptions() - Create configuration options

Channel Configuration

Route channels to different destinations

// Database logs → file (no color)
dbFile, _ := os.Create("logs/database.log")
dl.ConfigureChannel("database", dl.DefaultOptions().SetOutput(dbFile))

// HTTP logs → stderr as JSON
dl.ConfigureChannel("http", dl.DefaultOptions().JSON().SetOutput(os.Stderr))

// Error logs → console (colored)
dl.ConfigureChannel("errors", dl.DefaultOptions().Color())

Common Patterns

Contextual Logging

// Build context with chained attributes
logger := dl.ChannelLog("auth").
    With("user_id", 123).
    With("session", "abc-456")

logger.Info("login attempt")
logger.With("success", true).Info("authentication completed")

Application Integration

// Initialize with custom defaults
dl.Init(dl.DefaultOptions().SetLevel(slog.LevelDebug).Color())

// Different channels for different concerns
dl.ChannelLog("database").Info("connection established")
dl.ChannelLog("cache").Warn("memory usage high") 
dl.ChannelLog("api").Error("rate limit exceeded")

Format Examples

Pretty Console Output:

2024-01-15 14:30:25    INFO user authenticated user_id=123 session=abc-456
2024-01-15 14:30:26   ERROR |database| connection failed host=db.example.com

JSON Output:

{"time":"2024-01-15T14:30:25Z","level":"INFO","msg":"user authenticated","user_id":123}
{"time":"2024-01-15T14:30:26Z","level":"ERROR","channel":"database","msg":"connection failed"}

Examples

See examples/ for tutorials on basic logging, channel routing, and output formatting.


Part of the df framework - dynamic foundation for Go applications

Documentation

Index

Constants

View Source
const ChannelKey = "channel"

Variables

This section is empty.

Functions

func ConfigureChannel

func ConfigureChannel(name string, opts *Options)

ConfigureChannel sets a specific logger configuration for a channel

func Init

func Init(opts ...*Options)

Init initializes the logging system with the provided options. if no options are provided, uses default options.

func NewDfHandler

func NewDfHandler(opts *Options) slog.Handler

NewDfHandler creates a handler that supports both pretty and JSON modes

func NewPrettyHandler

func NewPrettyHandler(level slog.Level, options *Options) slog.Handler

NewPrettyHandler creates a new pretty handler - direct port from pfxlog

func NewPrettyHandlerWithChannel

func NewPrettyHandlerWithChannel(level slog.Level, options *Options, channelName string) slog.Handler

NewPrettyHandlerWithChannel creates a pretty handler with an optional channel name

func ReconfigureChannel

func ReconfigureChannel(name string, opts *Options)

ReconfigureChannel reconfigures an existing channel (alias for ConfigureChannel)

func RemoveChannel

func RemoveChannel(name string)

RemoveChannel removes a channel configuration, causing it to revert to defaults

Types

type Builder

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

Builder provides a fluent API for contextual logging, allowing attributes to be added before logging messages. preserves pfxlog's builder pattern semantics.

func ChannelLog

func ChannelLog(name string) *Builder

ChannelLog creates a logger with a specific channel attribute for categorizing log entries

func Log

func Log() *Builder

Log returns a general logger builder for adding contextual attributes

func (*Builder) Debug

func (b *Builder) Debug(msg string)

Debug logs a debug message with the accumulated attributes

func (*Builder) Debugf

func (b *Builder) Debugf(format string, args ...any)

Debugf logs a formatted debug message with the accumulated attributes

func (*Builder) Error

func (b *Builder) Error(msg string)

Error logs an error message with the accumulated attributes

func (*Builder) Errorf

func (b *Builder) Errorf(format string, args ...any)

Errorf logs a formatted error message with the accumulated attributes

func (*Builder) Fatal

func (b *Builder) Fatal(msg string)

Fatal logs a fatal error message with the accumulated attributes and exits the program

func (*Builder) Fatalf

func (b *Builder) Fatalf(format string, args ...any)

Fatalf logs a formatted fatal error message with the accumulated attributes and exits the program

func (*Builder) Info

func (b *Builder) Info(msg string)

Info logs an info message with the accumulated attributes

func (*Builder) Infof

func (b *Builder) Infof(format string, args ...any)

Infof logs a formatted info message with the accumulated attributes

func (*Builder) Warn

func (b *Builder) Warn(msg string)

Warn logs a warning message with the accumulated attributes

func (*Builder) Warnf

func (b *Builder) Warnf(format string, args ...any)

Warnf logs a formatted warning message with the accumulated attributes

func (*Builder) With

func (b *Builder) With(key string, value any) *Builder

With adds a key-value pair to the log context and returns a new builder. this allows for fluent chaining of contextual information.

type Channel

type Channel struct {
	Logger  *slog.Logger
	Options *Options
}

Channel represents a configured logging channel with its options and logger

type ChannelManager

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

ChannelManager manages per-channel logging with independent destinations

func NewChannelManager

func NewChannelManager(defaultOpts *Options) *ChannelManager

NewChannelManager creates a new channel log manager

func (*ChannelManager) ConfigureChannel

func (cm *ChannelManager) ConfigureChannel(name string, opts *Options)

ConfigureChannel sets a specific logger configuration for a channel

func (*ChannelManager) ConfigureDefaultChannel

func (cm *ChannelManager) ConfigureDefaultChannel(opts *Options)

ConfigureDefaultChannel updates the default options and recreates the default logger

func (*ChannelManager) GetChannel

func (cm *ChannelManager) GetChannel(name string) *Channel

GetChannel returns the full Channel for a specific channel Returns nil if the channel is not configured

func (*ChannelManager) GetChannelLogger

func (cm *ChannelManager) GetChannelLogger(name string) *slog.Logger

GetChannelLogger returns a logger for the specified channel

func (*ChannelManager) GetChannelOptions

func (cm *ChannelManager) GetChannelOptions(name string) *Options

GetChannelOptions returns a copy of the options for a specific channel Returns nil if the channel is not configured

func (*ChannelManager) GetDefaultChannel

func (cm *ChannelManager) GetDefaultChannel() *Channel

GetDefaultChannel returns a copy of the default log channel

func (*ChannelManager) GetDefaultLogger

func (cm *ChannelManager) GetDefaultLogger() *slog.Logger

GetDefaultLogger returns the default logger

func (*ChannelManager) GetDefaultOptions

func (cm *ChannelManager) GetDefaultOptions() *Options

GetDefaultOptions returns a copy of the default log options

func (*ChannelManager) IsChannelConfigured

func (cm *ChannelManager) IsChannelConfigured(name string) bool

IsChannelConfigured returns true if the channel has been explicitly configured

func (*ChannelManager) ListConfiguredChannels

func (cm *ChannelManager) ListConfiguredChannels() []string

ListConfiguredChannels returns the names of all configured channels

func (*ChannelManager) RemoveChannel

func (cm *ChannelManager) RemoveChannel(name string)

RemoveChannel removes a channel configuration, causing it to revert to defaults

type Options

type Options struct {
	Level           slog.Level
	UseJSON         bool
	UseColor        bool
	AbsoluteTime    bool
	StartTimestamp  time.Time
	TimestampFormat string
	TrimPrefix      string
	Output          io.Writer // output destination, defaults to os.Stdout
	CustomHandler   slog.Handler

	// level labels
	ErrorLabel   string
	WarningLabel string
	InfoLabel    string
	DebugLabel   string

	// colors
	TimestampColor string
	FunctionColor  string
	ChannelColor   string
	FieldsColor    string
	DefaultFgColor string // used for resetting colors
	ErrorColor     string
	WarningColor   string
	InfoColor      string
	DebugColor     string
}

Options configures the df logging system, compatible with pfxlog.Options

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions creates a default configuration with sensible defaults

func (*Options) Color

func (o *Options) Color() *Options

Color enables colored output with default color scheme

func (*Options) JSON

func (o *Options) JSON() *Options

JSON enables JSON output format

func (*Options) NoColor

func (o *Options) NoColor() *Options

NoColor disables colored output

func (*Options) Pretty

func (o *Options) Pretty() *Options

Pretty enables pretty-printed output format (default)

func (*Options) SetLevel

func (o *Options) SetLevel(level slog.Level) *Options

SetLevel allows setting the level threshold

func (*Options) SetOutput

func (o *Options) SetOutput(w io.Writer) *Options

SetOutput sets the output destination

func (*Options) SetTrimPrefix

func (o *Options) SetTrimPrefix(prefix string) *Options

SetTrimPrefix sets the function trim prefix

type PrettyHandler

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

PrettyHandler is a direct port of pfxlog's PrettyHandler for df

func (*PrettyHandler) Enabled

func (h *PrettyHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled implements slog.Handler.Enabled

func (*PrettyHandler) Handle

func (h *PrettyHandler) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler.Handle - direct port from pfxlog

func (*PrettyHandler) WithAttrs

func (h *PrettyHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.WithAttrs

func (*PrettyHandler) WithGroup

func (h *PrettyHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.WithGroup

Directories

Path Synopsis
examples
dl_02_channels command

Jump to

Keyboard shortcuts

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