logging

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package logging provides FlightRecorder integration for Go 1.25+. FlightRecorder enables lightweight, always-on tracing suitable for production.

Index

Constants

View Source
const (
	// ModelIDKey is used to store/retrieve ModelID from context.
	ModelIDKey contextKey = "model_id"

	// TokenInfoKey is used to store/retrieve token usage information.
	TokenInfoKey contextKey = "token_info"
)

Variables

This section is empty.

Functions

func GetModelID

func GetModelID(ctx context.Context) (core.ModelID, bool)

GetModelID retrieves ModelID from context.

func GetTokenInfo

func GetTokenInfo(ctx context.Context) (*core.TokenInfo, bool)

GetTokenInfo retrieves TokenInfo from context.

func InitGlobalFlightRecorder

func InitGlobalFlightRecorder(opts ...FlightRecorderOption)

InitGlobalFlightRecorder initializes and starts the global FlightRecorder. Safe to call multiple times; only the first call has effect. If the flight recorder fails to start, it logs the error and continues without recording.

func SetLogger

func SetLogger(l *Logger)

SetLogger allows setting a custom configured logger as the global instance.

func TraceLog

func TraceLog(ctx context.Context, category, message string)

TraceLog logs a message to the trace at the current point. Useful for marking significant events in the trace timeline.

func TraceRegion

func TraceRegion(ctx context.Context, name string) func()

TraceRegion wraps trace.WithRegion for convenient span creation. Use this to annotate important code sections in traces.

Example:

defer TraceRegion(ctx, "ProcessModule")()

func TraceTask

func TraceTask(ctx context.Context, name string) (context.Context, func())

TraceTask creates a trace task for tracking high-level operations. Returns a new context and an end function.

Example:

ctx, endTask := TraceTask(ctx, "Optimization")
defer endTask()

func WithModelID

func WithModelID(ctx context.Context, modelID core.ModelID) context.Context

WithModelID adds a ModelID to the context.

func WithTokenInfo

func WithTokenInfo(ctx context.Context, info *core.TokenInfo) context.Context

WithTokenInfo adds TokenInfo to the context.

Types

type Config

type Config struct {
	Severity      Severity
	Outputs       []Output
	SampleRate    uint32
	DefaultFields map[string]interface{}
}

Config allows flexible logger configuration.

type ConsoleOutput

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

ConsoleOutput formats logs for human readability.

func NewConsoleOutput

func NewConsoleOutput(useStderr bool, opts ...ConsoleOutputOption) *ConsoleOutput

func (*ConsoleOutput) Close

func (c *ConsoleOutput) Close() error

Close cleans up any resources.

func (*ConsoleOutput) Sync

func (c *ConsoleOutput) Sync() error

func (*ConsoleOutput) Write

func (o *ConsoleOutput) Write(e LogEntry) error

type ConsoleOutputOption

type ConsoleOutputOption func(*ConsoleOutput)

func WithColor

func WithColor(enabled bool) ConsoleOutputOption

type FileOutput

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

FileOutput formats logs and writes them to a file.

func NewFileOutput

func NewFileOutput(path string, opts ...FileOutputOption) (*FileOutput, error)

NewFileOutput creates a new file-based logger output.

func (*FileOutput) Close

func (f *FileOutput) Close() error

Close closes the file.

func (*FileOutput) Sync

func (f *FileOutput) Sync() error

Sync flushes any buffered data to the underlying file.

func (*FileOutput) Write

func (f *FileOutput) Write(e LogEntry) error

Write implements the Output interface.

type FileOutputOption

type FileOutputOption func(*FileOutput)

FileOutputOption is a functional option for configuring FileOutput.

func WithBufferSize

func WithBufferSize(size int) FileOutputOption

WithBufferSize sets the internal buffer size for writes.

func WithFormatter

func WithFormatter(formatter LogFormatter) FileOutputOption

WithFormatter sets a custom log formatter.

func WithJSONFormat

func WithJSONFormat(enabled bool) FileOutputOption

WithJSONFormat configures the output to use JSON formatting.

func WithRotation

func WithRotation(maxSizeBytes int64, maxFiles int) FileOutputOption

WithRotation enables log file rotation.

type FlightRecorder

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

FlightRecorder wraps Go 1.25's runtime/trace.FlightRecorder for production diagnostics. It maintains a ring buffer of recent trace data that can be dumped on-demand (e.g., when an error occurs or performance degrades).

Usage:

fr := NewFlightRecorder(WithMinAge(10 * time.Second))
fr.Start()
defer fr.Stop()

// When an interesting event occurs:
fr.Snapshot("error_occurred.trace")

func GlobalFlightRecorder

func GlobalFlightRecorder() *FlightRecorder

GlobalFlightRecorder returns a shared FlightRecorder instance. Initialize with InitGlobalFlightRecorder before use.

func NewFlightRecorder

func NewFlightRecorder(opts ...FlightRecorderOption) *FlightRecorder

NewFlightRecorder creates a new FlightRecorder with the given options. The FlightRecorder uses Go 1.25's runtime/trace.FlightRecorder which maintains a ring buffer of trace data with minimal overhead (~1% CPU).

func (*FlightRecorder) Enabled

func (fr *FlightRecorder) Enabled() bool

Enabled returns true if the flight recorder is currently running.

func (*FlightRecorder) Snapshot

func (fr *FlightRecorder) Snapshot(filename string) error

Snapshot writes the current trace buffer to a file. Call this when an interesting event occurs (error, slow request, etc.) to capture what happened leading up to that moment.

func (*FlightRecorder) SnapshotOnError

func (fr *FlightRecorder) SnapshotOnError(err error, filename string) error

SnapshotOnError is a helper that takes a snapshot when an error occurs. Returns the original error for chaining.

Example:

result, err := module.Process(ctx, inputs)
if err != nil {
    return fr.SnapshotOnError(err, "module_error.trace")
}

func (*FlightRecorder) Start

func (fr *FlightRecorder) Start() error

Start begins recording trace data into the ring buffer. This is safe to call in production with minimal overhead.

func (*FlightRecorder) Stop

func (fr *FlightRecorder) Stop()

Stop stops recording trace data.

type FlightRecorderOption

type FlightRecorderOption func(*FlightRecorder)

FlightRecorderOption configures a FlightRecorder.

func WithMaxBytes

func WithMaxBytes(n uint64) FlightRecorderOption

WithMaxBytes sets the maximum size of the trace buffer in bytes. This takes precedence over MinAge. If 0, the maximum is implementation defined.

func WithMinAge

func WithMinAge(d time.Duration) FlightRecorderOption

WithMinAge sets the minimum age of events to keep in the trace buffer. Default is 10 seconds. Longer durations capture more history but use more memory.

type JSONFormatter

type JSONFormatter struct{}

JSONFormatter implements LogFormatter for JSON output.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(e LogEntry) string

Format formats a LogEntry as JSON.

type LogEntry

type LogEntry struct {
	// Standard fields
	Time     int64
	Severity Severity
	Message  string
	File     string
	Line     int
	Function string
	TraceID  string // Added trace ID field

	// LLM-specific fields
	ModelID   string          // The LLM model being used
	TokenInfo *core.TokenInfo // Token usage information
	Latency   int64           // Operation duration in milliseconds
	Cost      float64         // Operation cost in dollars

	// General structured data
	Fields map[string]interface{}
}

LogEntry represents a structured log record with fields particularly relevant to LLM operations.

type LogFormatter

type LogFormatter interface {
	Format(entry LogEntry) string
}

LogFormatter defines an interface for formatting log entries.

type Logger

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

Logger provides the core logging functionality.

func GetLogger

func GetLogger() *Logger

GetLogger returns the global logger instance.

func NewLogger

func NewLogger(cfg Config) *Logger

NewLogger creates a new logger with the given configuration.

func (*Logger) Debug

func (l *Logger) Debug(ctx context.Context, format string, args ...interface{})

Regular severity-based logging methods.

func (*Logger) Error

func (l *Logger) Error(ctx context.Context, format string, args ...interface{})

func (*Logger) Fatal

func (l *Logger) Fatal(ctx context.Context, msg string)

func (*Logger) Fatalf

func (l *Logger) Fatalf(ctx context.Context, format string, args ...interface{})

func (*Logger) Info

func (l *Logger) Info(ctx context.Context, format string, args ...interface{})

func (*Logger) PromptCompletion

func (l *Logger) PromptCompletion(ctx context.Context, prompt, completion string, tokenInfo *core.TokenInfo)

LLM-specific logging methods.

func (*Logger) Warn

func (l *Logger) Warn(ctx context.Context, format string, args ...interface{})

type Output

type Output interface {
	Write(LogEntry) error
	Sync() error
	Close() error
}

Output interface allows for different logging destinations.

type Severity

type Severity int32

Severity represents log levels with clear mapping to different stages of LLM operations.

const (
	DEBUG Severity = iota
	INFO
	WARN
	ERROR
	FATAL
)

func ParseSeverity

func ParseSeverity(level string) Severity

ParseSeverity converts a string to a Severity level. Returns INFO level for unknown strings.

func (Severity) String

func (s Severity) String() string

String provides human-readable severity levels.

type TextFormatter

type TextFormatter struct {
	// Whether to include timestamps in the output
	IncludeTimestamp bool
	// Whether to include file and line information
	IncludeLocation bool
	// Whether to include stack traces for errors
	IncludeStackTrace bool
}

TextFormatter implements LogFormatter with a simple text format.

func (*TextFormatter) Format

func (f *TextFormatter) Format(e LogEntry) string

Format formats a LogEntry as text.

Jump to

Keyboard shortcuts

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