Documentation
¶
Overview ¶
Package lane provides a context-aware logging and correlation library.
A "lane" is a context that integrates logging, combining Go's `log` package with its `context`. A lane is designed to be passed into all functions, serving as a regular `context` for tasks like cancellation, while also replacing `log` for logging purposes.
The logging interface offers various tools for detailed diagnostics, including correlation IDs, stack traces, easy logging of structs (even private fields), log capturing for test verification, recording structural differences, and more.
Index ¶
- Constants
- func AddFilterTee(parent Lane, tee Lane, pattern string)
- func CaptureObject(obj any) (v any)
- func DiffObjects(a, b any) string
- func LogObject(l Lane, level LaneLogLevel, message string, obj any)
- func NewSlogHandler(l Lane) slog.Handler
- type FilterFunc
- type Lane
- func NewDiskLane(ctx OptionalContext, logFile string) (l Lane, err error)
- func NewEmbeddedLogLane(onCreate OnCreateLane, startingCtx OptionalContext) (l Lane, err error)
- func NewFilterLane(wrapped Lane, filter FilterFunc) Lane
- func NewLevelFilterLane(wrapped Lane, minLevel LaneLogLevel) Lane
- func NewLogLane(ctx OptionalContext) Lane
- func NewLogLaneWithCR(ctx OptionalContext) Lane
- func NewNullLane(ctx OptionalContext) Lane
- func NewRegexFilterLane(wrapped Lane, pattern string) Lane
- type LaneEvent
- type LaneIdKey
- type LaneLogLevel
- type LaneMetadata
- type LogLane
- type MetadataStore
- type OnCreateLane
- type OptionalContext
- type Panic
- type TestingLane
Constants ¶
const LogLaneIdKey = LaneIdKey("log_lane_id")
LogLaneIdKey is the context key for the lane ID.
const ParentLaneIdKey = LaneIdKey("parent_lane_id")
ParentLaneIdKey is the context key for the parent lane ID.
Variables ¶
This section is empty.
Functions ¶
func AddFilterTee ¶ added in v1.32.0
AddFilterTee adds a tee to the parent lane, optionally wrapping it with a regex filter. If pattern is empty, the tee is added directly without filtering. If pattern is provided, the tee is wrapped with NewRegexFilterLane before being added.
Example:
mainLane := NewLogLane(nil) AddFilterTee(mainLane, NewDiskLane(nil, "/var/log/audit.log"), `^\[AUDIT\]`) AddFilterTee(mainLane, NewDiskLane(nil, "/var/log/all.log"), "")
func CaptureObject ¶
CaptureObject converts an arbitrary object into a JSON-renderable object. Unlike standard json.Marshal, this function includes private fields and follows pointers to capture the full state of the object.
func DiffObjects ¶
DiffObjects generates a display string describing the differences between [a] and [b], or an empty string if no differences exist.
func LogObject ¶
func LogObject(l Lane, level LaneLogLevel, message string, obj any)
LogObject logs an entire object to the lane.
func NewSlogHandler ¶ added in v1.34.0
NewSlogHandler returns a structured logging handler that routes records through l. Records retain standard slog attributes and groups, then use the lane's configured log level, filters, tees, and output destination.
Types ¶
type FilterFunc ¶ added in v1.32.0
type FilterFunc func(lane Lane, level LaneLogLevel, message string) bool
FilterFunc is a function that determines whether a log message should be passed through. It receives the lane (for accessing journey ID, metadata, etc.), the log level, and the formatted message. Returns true if the message should be logged, false otherwise.
func NewLevelFilter ¶ added in v1.32.0
func NewLevelFilter(minLevel LaneLogLevel) FilterFunc
NewLevelFilter creates a filter function based on minimum log level. Use this when you need to combine filters or use NewFilterLane directly.
func NewRegexFilter ¶ added in v1.32.0
func NewRegexFilter(pattern string) FilterFunc
NewRegexFilter creates a filter function that matches messages against a regular expression. Use this when you need to combine filters or use NewFilterLane directly.
type Lane ¶
type Lane interface {
context.Context
// Provides the correlation ID of the lane
LaneId() string
// Provides the journey ID (correlation across multiple processs/services/systems)
JourneyId() string
// Assigns an 'outer' correlation ID, intended for an end to end correlation that
// may include an ID generated by some other part of the system.
//
// The ID will be truncated to 10 characters.
//
// Once set, log messages will include this ID along with the lane ID.
SetJourneyId(id string)
// Controls the log filtering
SetLogLevel(newLevel LaneLogLevel) (priorLevel LaneLogLevel)
// Returns true if the specified log level will produce output.
// Note: This only checks the log level threshold, not message-based filters.
// For FilterLane, messages may still be filtered even if this returns true.
IsLevelEnabled(level LaneLogLevel) bool
// Sets a lane metadata value (even if the lane type does not log it)
SetMetadata(key, val string)
// Gets a lane metadata value (even if the lane type does not log it)
GetMetadata(key string) string
// Trace, intended for checkpoint information. Messages formated with fmt.Sprint().
Trace(args ...any)
// Trace, intended for checkpoint information. Messages formated with fmt.Sprintf().
Tracef(format string, args ...any)
// Trace, intended for checkpoint information. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
TraceObject(message string, obj any)
// Debug, intended for diagnostic information such as unusual conditions or helpful variable values. Messages formated with fmt.Sprint().
Debug(args ...any)
// Debug, intended for diagnostic information such as unusual conditions or helpful variable values. Messages formated with fmt.Sprintf().
Debugf(format string, args ...any)
// Debug, intended for diagnostic information such as unusual conditions or helpful variable values. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
DebugObject(message string, obj any)
// Info, intended for details as the app runs in a healthy state, such as end user requests and results. Messages formated with fmt.Sprint().
Info(args ...any)
// Info, intended for details as the app runs in a healthy state, such as end user requests and results. Messages formated with fmt.Sprintf().
Infof(format string, args ...any)
// Info, intended for details as the app runs in a healthy state, such as end user requests and results. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
InfoObject(message string, obj any)
// Warn, intended for recoverable, ignorable or ambiguous errors. Messages formated with fmt.Sprint().
Warn(args ...any)
// Warn, intended for recoverable, ignorable or ambiguous errors. Messages formated with fmt.Sprintf().
Warnf(format string, args ...any)
// Warn, intended for recoverable, ignorable or ambiguous errors. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
WarnObject(message string, obj any)
// Error, intended for application faults that alert or explain unwanted conditions. Messages formated with fmt.Sprint().
Error(args ...any)
// Error, intended for application faults that alert or explain unwanted conditions. Messages formated with fmt.Sprintf().
Errorf(format string, args ...any)
// Error, intended for application faults that alert or explain unwanted conditions. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
ErrorObject(message string, obj any)
// Severe error, intended for details about why an application will soon terminate. Messages formated with fmt.Sprint().
PreFatal(args ...any)
// Severe error, intended for details about why an application will soon terminate. Messages formated with fmt.Sprintf().
PreFatalf(format string, args ...any)
// Severe error, intended for details about why an application will soon terminate. Object [obj] is converted to JSON, including private fields, and concatenated to [message].
PreFatalObject(message string, obj any)
// Fatal error, intended for details about why an application can't continue and must terminate. Messages formated with fmt.Sprint(). The app panics after logging completes.
Fatal(args ...any)
// Fatal error, intended for details about why an application can't continue and must terminate. Messages formated with fmt.Sprintf(). The app panics after logging completes.
Fatalf(format string, args ...any)
// Fatal error, intended for details about why an application can't continue and must terminate. Messages formated with fmt.Sprintf(). Object [obj] is converted to JSON, including private fields, and concatenated to [message].
FatalObject(message string, obj any)
// Logs the stack
LogStack(message string)
// Logs the stack, trimming the top of the stack by the number of [skippedCallers] specified
LogStackTrim(message string, skippedCallers int)
// Set a limit on the message length, or less than 1 for no limit.
SetLengthConstraint(maxLength int) int
// Exposes access to the underlying log object.
Logger() *log.Logger
// SlogLogger returns a structured logger that routes records through this lane.
SlogLogger() *slog.Logger
// SlogHandler returns the structured logging handler used by SlogLogger.
SlogHandler() slog.Handler
Close()
// Makes a lane for a child activity that needs its own correlation ID. For example a server will derive a new lane for each client connection.
Derive() Lane
// Makes a lane for a child activity that needs its own correlation ID, with the cancelable context.
DeriveWithCancel() (Lane, context.CancelFunc)
// Makes a lane for a child activity that needs its own correlation ID, with the cancelable context.
// The cancel function can specify an error to indicate why the context was canceled.
DeriveWithCancelCause() (Lane, context.CancelCauseFunc)
// Makes a lane for a child activity that needs its own correlation ID, removing the cancelable context.
DeriveWithoutCancel() Lane
// Makes a lane for a child activity that needs its own correlation ID, with the time-canceled context.
DeriveWithDeadline(deadline time.Time) (Lane, context.CancelFunc)
// Makes a lane for a child activity that needs its own correlation ID, with the time-canceled context.
// The [cause] argument provides an error to use for timeout expiration.
DeriveWithDeadlineCause(deadline time.Time, cause error) (Lane, context.CancelFunc)
// Makes a lane for a child activity that needs its own correlation ID, with the relative time-canceled context.
DeriveWithTimeout(duration time.Duration) (Lane, context.CancelFunc)
// Makes a lane for a child activity that needs its own correlation ID, with the relative time-canceled context.
// The [cause] argument provides an error to use for timeout expiration.
DeriveWithTimeoutCause(duration time.Duration, cause error) (Lane, context.CancelFunc)
// Used to maintain the lane configuration while changing the context.
DeriveReplaceContext(ctx OptionalContext) Lane
// Turns on stack trace logging.
EnableStackTrace(level LaneLogLevel, enable bool) (wasEnabled bool)
// AddTee attaches a receiver lane to the sender lane. Log messages from the sender lane are
// forwarded to the receiver lane [l], but retain the sender lane's lane ID and journey ID
// instead of the receiver's IDs.
AddTee(l Lane)
// Disconnects the other lane from the tee.
RemoveTee(l Lane)
// Provides the current tee list
Tees() []Lane
// Intercepts Panic, allowing the test to prevent the executable from crashing, and validate
// an injected fatal error. Use this with care, and be sure to call runtime.Goexit() so that
// the test version of Panic doesn't return.
SetPanicHandler(handler Panic)
// Gets the parent lane, or untyped nil if no parent.
Parent() Lane
}
func NewDiskLane ¶
func NewDiskLane(ctx OptionalContext, logFile string) (l Lane, err error)
NewDiskLane creates a new lane that logs to a file.
func NewEmbeddedLogLane ¶
func NewEmbeddedLogLane(onCreate OnCreateLane, startingCtx OptionalContext) (l Lane, err error)
NewEmbeddedLogLane initializes a LogLane for a more sophisticated lane type that embeds a log lane.
- onCreate creates a new instance of the outer lane and provides the embedded log lane.
- startingCtx provides an optional context instance, to start a lane from a pre-existing context
func NewFilterLane ¶ added in v1.32.0
func NewFilterLane(wrapped Lane, filter FilterFunc) Lane
NewFilterLane creates a new lane that wraps another lane and filters log messages based on the provided filter function. The filter receives the log level and formatted message, and should return true to allow the message through, false to block it.
All non-logging methods (context operations, metadata, etc.) are passed through unchanged to the wrapped lane.
For common use cases, see NewRegexFilterLane and NewLevelFilterLane.
func NewLevelFilterLane ¶ added in v1.32.0
func NewLevelFilterLane(wrapped Lane, minLevel LaneLogLevel) Lane
NewLevelFilterLane creates a filtered lane that only passes messages at or above the minimum level.
Example:
// Only log warnings and errors errorLane := lane.NewLevelFilterLane(diskLane, lane.LogLevelWarn)
func NewLogLane ¶
func NewLogLane(ctx OptionalContext) Lane
NewLogLane creates a new lane that logs to the standard Go log output.
func NewLogLaneWithCR ¶
func NewLogLaneWithCR(ctx OptionalContext) Lane
NewLogLaneWithCR creates a new lane that logs to the standard Go log output, ensuring \r\n line endings. This is useful for terminals that require CR/LF, such as the VS Code terminal.
func NewNullLane ¶
func NewNullLane(ctx OptionalContext) Lane
NewNullLane creates a new lane that discards all log output.
func NewRegexFilterLane ¶ added in v1.32.0
NewRegexFilterLane creates a filtered lane that only passes messages matching the regex pattern.
Example:
// Capture only [AUDIT] messages auditLane := lane.NewRegexFilterLane(diskLane, `^\[AUDIT\]`) // Capture messages containing "error" or "warning" (case-insensitive) errorLane := lane.NewRegexFilterLane(diskLane, `(?i)(error|warning)`)
type LaneIdKey ¶
type LaneIdKey string
LaneIdKey is the type used for context keys related to lane IDs.
type LaneLogLevel ¶
type LaneLogLevel int
LaneLogLevel indicates the severity of a log message.
const ( // LogLevelTrace is for checkpoint information. LogLevelTrace LaneLogLevel = iota // LogLevelDebug is for diagnostic information. LogLevelDebug // LogLevelInfo is for healthy state information. LogLevelInfo // LogLevelWarn is for recoverable errors. LogLevelWarn // LogLevelError is for application faults. LogLevelError // LogLevelFatal is for termination conditions. LogLevelFatal // LogLevelStack is a special level for stack trace logging. LogLevelStack )
type LaneMetadata ¶
type LaneMetadata interface {
// SetOwner links the metadata to the owning lane.
SetOwner(l Lane)
// SetMetadata sets a key-value pair in the metadata.
// This value will be propagated to any attached tee lanes.
SetMetadata(key, value string)
// GetMetadata retrieves the value for a given key.
GetMetadata(key string) string
// MetadataMap returns a copy of all metadata.
MetadataMap() map[string]string
}
LaneMetadata is the interface for managing metadata associated with a lane. Metadata consists of key-value pairs that provide additional context. These pairs are often used by structured logging lanes (like OpenSearch) to include extra fields in the log records.
type LogLane ¶
type LogLane interface {
Lane
// AddCR controls whether a carriage return is added to log messages.
AddCR(shouldAdd bool) (prior bool)
// SetFlagsMask sets the flags mask for the underlying logger.
// This allows controlling the output format of the standard Go logger,
// such as including or excluding date, time, and file location.
// See the constants in the standard "log" package (e.g., log.Ldate, log.Ltime).
SetFlagsMask(mask int) (prior int)
// contains filtered or unexported methods
}
LogLane is the interface for a lane that logs to an output.
func AllocEmbeddedLogLane ¶
func AllocEmbeddedLogLane() LogLane
AllocEmbeddedLogLane is used by extended lane types (such as DiskLane or OpenSearchLane) to allocate the embedded LogLane instance. This is typically called within the OnCreateLane callback passed to NewEmbeddedLogLane.
type MetadataStore ¶
type MetadataStore struct {
// contains filtered or unexported fields
}
Common implementation of metadata
func (*MetadataStore) GetMetadata ¶
func (ms *MetadataStore) GetMetadata(key string) string
GetMetadata retrieves the lane's metadata value if it is set
func (*MetadataStore) MetadataMap ¶
func (ms *MetadataStore) MetadataMap() map[string]string
MetadataMap returns a copy of the metadata map
func (*MetadataStore) SetMetadata ¶
func (ms *MetadataStore) SetMetadata(key, value string)
SetMetadata sets the lane's metadata value, overwriting a prior value if one was set
func (*MetadataStore) SetOwner ¶
func (ms *MetadataStore) SetOwner(l Lane)
SetOwner is used in lane object creation to link the metadata interface to the owning lane
type OnCreateLane ¶
OnCreateLane is a callback invoked when a derived context is created. It is used by log lane types that embed a log lane. It allows the outer lane type to make its lane-specific object. The callback must provide newLane and ll. Returning non-nil writer is optional.
type OptionalContext ¶
OptionalContext is an alias for context.Context. It is used to indicate that nil is an acceptable value.
type Panic ¶
type Panic func()
Panic is a function type used for replacing the default panic behavior, primarily for testing.
type TestingLane ¶
type TestingLane interface {
Lane
// Renders all of the captured log messages into a single string.
EventsToString() string
// Checks for log messages to exactly match the specified events.
VerifyEvents(eventList []*LaneEvent) (match bool)
// Checks for log messages to match the specified events. Ignores
// log events that do not match.
FindEvents(eventList []*LaneEvent) (found bool)
// Uses a descriptor to create an event list, then calls VerifyEvents.
// The descriptor is a simple format where log messages are separated
// by line breaks, and each line is "SEVERITY\tExpected message". The
// other details that get logged, such as timestamp and correlation ID,
// are ignored.
VerifyEventText(eventText string) (match bool)
// Similar to VerifyEventText, except that lines that do not match
// are ignored.
FindEventText(eventText string) (found bool)
// Checks if the string occurs anywhere in the logged text
Contains(text string) (found bool)
// Controls whether to capture child lane activity (wanted=true) or not.
WantDescendantEvents(wanted bool) (prior bool)
// Retrieves metadata
GetMetadata(key string) string
// Controls whether stack traces are a single event or an event per
// call stack line.
EnableSingleLineStackTrace(wanted bool) (prior bool)
// contains filtered or unexported methods
}
TestingLane is a lane that captures log messages for verification in tests.
func NewTestingLane ¶
func NewTestingLane(ctx OptionalContext) TestingLane
NewTestingLane creates a new lane that captures log messages for testing purposes.