lane

package module
v1.34.2 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 21 Imported by: 10 modules, 9 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-lane

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.

Related projects extend this unified logging approach, such as go-lane-gin and go-lane-opensearch.

Basic Use

import (
    "context"
    "github.com/jimsnab/go-lane"
)

func myFunc() {
    l := lane.NewLogLane(context.Background())

    l.Info("log something")
}

At the root, a lane needs a context, and that is typically nil or context.Background(). From there, instead of passing a context instance as the first parameter, pass the lane l.

func someFunc(l lane.Lane) {
     // use l like a context instance, or call one of its interface members
}

Interface

Lane Instance

Lane interface {
	context.Context
	LaneId() string
	SetJourneyId(id string)
	SetLogLevel(newLevel LaneLogLevel) (priorLevel LaneLogLevel)
	IsLevelEnabled(level LaneLogLevel) bool

	Trace(args ...any)
	Tracef(format string, args ...any)
	TraceObject(message string, obj any)

	Debug(args ...any)
	Debugf(format string, args ...any)
	DebugObject(message string, obj any)

	Info(args ...any)
	Infof(format string, args ...any)
	InfoObject(message string, obj any)

	Warn(args ...any)
	Warnf(format string, args ...any)
	WarnObject(message string, obj any)

	Error(args ...any)
	Errorf(format string, args ...any)
	ErrorObject(message string, obj any)

	PreFatal(args ...any)
	PreFatalf(format string, args ...any)
	PreFatalObject(message string, obj any)

	Fatal(args ...any)
	Fatalf(format string, args ...any)
	FatalObject(message string, obj any)

	LogStack(message string)
	LogStackTrim(message string, skippedCallers int)

	Logger() *log.Logger
	Close()

	Derive() Lane

	DeriveWithCancel() (Lane, context.CancelFunc)
	DeriveWithCancelCause() (Lane, context.CancelCauseFunc)
	DeriveWithoutCancel() (Lane, context.CancelFunc)

	DeriveWithDeadline(deadline time.Time) (Lane, context.CancelFunc)
	DeriveWithDeadlineCause(deadline time.Time, cause error) (Lane, context.CancelFunc)

	DeriveWithTimeout(duration time.Duration) (Lane, context.CancelFunc)
	DeriveWithTimeoutCause(duration time.Duration, cause error) (Lane, context.CancelFunc)
	
	DeriveReplaceContext(ctx OptionalContext) Lane

	EnableStackTrace(level LaneLogLevel, enable bool) (wasEnabled bool)

	AddTee(l Lane)
	RemoveTee(l Lane)

	SetPanicHandler(handler Panic)

	Parent() Lane
}

For the most part, application code will use the logging functions (Trace, Debug, etc.).

Each log level offers:

  • a Sprint version (e.g., Info or Error)
  • a Sprintf version (e.g., Infof or Errorf)
  • an object logger (e.g., InfoObject or ErrorObject)

The object logger converts an object to JSON, including private fields.

Structured Logging

SlogLogger() returns a standard slog.Logger that routes records through the lane. It preserves slog attributes, groups, and custom levels while applying the lane's level filtering, tees, and filters. Lane and journey IDs, along with lane metadata, are added to every structured record.

logger := l.SlogLogger().With("component", "api")
logger.InfoContext(l, "request complete", "status", 200)

Use SlogHandler() when an integration accepts an slog.Handler.

A correlation ID is provided via LaneId(), which is automatically included in logged messages.

When spawning goroutines, pass l (the lane) around. Use one of the Derive functions if a new correlation ID is needed.

Optionally, an "outer ID" can be assigned with SetJourneyId(). This function is useful for correlating transactions that involve multiple lanes or for linking with an externally generated ID. The journey ID is inherited by derived lanes.

For example, a front-end application might generate a journey ID and pass it with its REST request to a Go server that logs activity via lanes. By setting the journey ID to match what the front end generated, the lanes will be correlated with front-end logging.

Another lane can "tee" from a source lane. For instance, you might tee a testing lane from a logging lane, allowing a unit test to verify that certain log messages are generated during the test.

When a log message is sent to a tee, the receiving lane will log the journey and lane IDs using the originating IDs, and not the receiving lane's IDs.

Utility Functions

LogObject

lane.LogObject provides access to the common implementation of InfoObject, ErrorObject, etc., for implementing extended lane types.

CaptureObject

lane.CaptureObject exposes the function that turns an object into one that can be used with json.Marshal without losing private data. It does not retain json type annotations however.

DiffObject

lane.DiffObject returns a string that describes the differences between two objects, or an empty string if the objects are identical.

For example, assume a and b are instances of a street address struct, and are passed into a function like this:

func compare(l lane.Lane, a, b any) {
	if !reflect.DeepEqual(a, b) {
		l.Infof("address change: %s", lane.DiffObject(a, b))
	}
}

Assume street addresses a and b are different. The log output will look something like this:

2024/07/11 13:20:26 INFO {e87ed2b1ed} address change: [Address: "2727 S Parker Rd" -> "407 Weston St"][City: "Dallas" -> "Kirby"][Zip: "75233" -> "78219"]

Only the changed fields are logged. Notice Texas is not shown in the change.

Metadata

Lanes support attaching metadata, which are key-value pairs that provide additional context to the lane.

l.SetMetadata("request_id", "12345")
l.SetMetadata("user", "jdoe")

Metadata is particularly useful when using structured logging lanes, such as go-lane-opensearch. In such cases, the metadata pairs are included as fields in the structured log document (e.g., JSON), allowing for powerful filtering and searching in the log aggregation system.

Metadata is propagated to "tee" lanes. For example, if you have a LogLane (stdout) and tee it to an OpenSearchLane, setting metadata on the main lane will ensure it appears in the OpenSearch documents.

Types of Lanes

  • NewLogLane log messages go to the standard Go log infrastructure. Access the log instance via Logger() to set flags, add a prefix, or change output I/O.

  • NewDiskLane like a "log lane" but writes output to a file.

  • NewTestingLane captures log messages into a buffer and provides helpers for unit tests:

    • VerifyEvents(), VerifyEventText() - check for exact log messages
    • FindEvents(), FindEventText() - check logged messages for specific logging events
    • EventsToString() - stringify the logged messages for verification by the unit test
    • Contains() - checks if text is found in any captured log message

    A testing lane also has the API WantDescendantEvents() to enable (or disable) capture of derived testing lane activity. This is useful to verify a child task reaches an expected logging point.

  • NewNullLane creates a lane that does not log but still has the context functionality. Logging is similar to log.SetOutput(io.Discard) - fatal errors still terminate the app.

  • NewFilterLane wraps any lane and filters log messages based on a predicate function. This is useful for routing specific messages to different destinations, such as audit logs.

Check out other projects, such as go-lane-gin or go-lane-opensearch for additional lane types.

Filtering Messages

Filter lanes allow you to route specific log messages to different destinations based on content or severity.

mainLane := lane.NewLogLane(nil)

// Audit log - only [AUDIT] messages
lane.AddFilterTee(mainLane, lane.NewDiskLane(nil, "/var/log/audit.log"), `^\[AUDIT\]`)

// Debug log - everything (no filter)
lane.AddFilterTee(mainLane, lane.NewDiskLane(nil, "/var/log/debug.log"), "")
Advanced: Custom Filters

For complex logic, use NewFilterLane with a custom function. The filter receives the lane (for accessing journey ID, metadata, etc.), log level, and message:

// Route based on metadata (e.g., tenant ID)
tenantFilter := func(lane lane.Lane, level lane.LaneLogLevel, msg string) bool {
    return lane.GetMetadata("tenant") == "acme-corp"
}
tenantLane := lane.NewFilterLane(tenantDiskLane, tenantFilter)

// Complex: errors with [CRITICAL] OR any warning, but only for specific journey
criticalFilter := func(lane lane.Lane, level lane.LaneLogLevel, msg string) bool {
    isTargetJourney := strings.HasPrefix(lane.JourneyId(), "prod-")
    if level == lane.LogLevelError && strings.HasPrefix(msg, "[CRITICAL]") {
        return isTargetJourney
    }
    return level == lane.LogLevelWarn && isTargetJourney
}
filteredLane := lane.NewFilterLane(diskLane, criticalFilter)
mainLane.AddTee(filteredLane)

Stack Trace

Stacks can be logged using LogStack(), or LogStackTrim() to remove some of the callers from the top of the stack.

Stack trace logging can be enabled on a per level basis. For example, to enable stack trace output for ERROR:

func example() {
	l := NewLogLane(context.Background())
	l.EnableStackTrace(lane.LogLevelError, true)
	l.Error("sample")   // stack trace is logged also
}

The test lane includes a special option, EnableSingleLineStackTrace(), which logs the entire stack trace as a single test event. This creates a more predictable test event list compared to traditional stack traces, where each caller is logged as a separate event.

Max Message Length

The length of a single log message can be length-constrained. Call SetLengthConstraint() to do that.

Panic Handler

Fatal messages trigger a panic. In test code, the panic handler can be replaced to verify that a fatal condition is reached during the test.

An ordinary unrecovered panic will prevent other goroutines from continuing, as the process typically terminates on a panic. A test must ensure that all goroutines started by the test are stopped by the replacement panic handler.

At a minimum, the test's replacement panic handler must prevent the panicking goroutine from continuing execution (it should call runtime.Goexit()).

OptionalContext

lane.OptionalContext is an alias type for context.Context. It's used because linters want to enforce callers to call context.Background() or context.TODO(). Callers can certainly do that, but the linter rule is questionable -- just pass nil, what's the problem?

Parent Context

Ordinary context does not provide a way to navigate to a parent. But sometimes this is wanted, such as when implementing diagnostics.

The parent lane ID is available as a context.Value() under the name ParentLaneIdKey:

The parent lane (which is a context) is also available by calling Lane.Parent().

	lOne := lane.NewLogLane(nil)
	lTwo := lOne.Derive()
	fmt.Printf("lOne %s == lTwo's parent %v\n", lOne.LaneId(), lTwo.Value(lane.ParentLaneIdKey))
	
	lThree := lTwo.Parent()
	fmt.Printf("lOne %s == lThree %s\n", lOne.LaneId(), lThree.LaneId())

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

View Source
const LogLaneIdKey = LaneIdKey("log_lane_id")

LogLaneIdKey is the context key for the lane ID.

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

func AddFilterTee(parent Lane, tee Lane, pattern string)

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

func CaptureObject(obj any) (v any)

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

func DiffObjects(a, b any) string

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

func NewSlogHandler(l Lane) slog.Handler

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

func NewRegexFilterLane(wrapped Lane, pattern string) Lane

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 LaneEvent

type LaneEvent struct {
	Id      string
	Level   string
	Message string
}

LaneEvent represents a single log event captured by TestingLane.

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

type OnCreateLane func(parentLane Lane) (newLane Lane, ll LogLane, writer *log.Logger, err error)

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

type OptionalContext context.Context

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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