utils

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextWithLogLevel

func ContextWithLogLevel(ctx context.Context, level int) context.Context

ContextWithLogLevel returns a context with a specific log level. This can be used to temporarily increase log verbosity for debugging.

Parameters:

  • ctx: The parent context
  • level: The log level to set

Returns:

  • context.Context: A new context with the log level

func CorrelationContext

func CorrelationContext(ctx context.Context, correlationID string) (context.Context, string)

CorrelationContext creates a context with a correlation ID. This helps track related events across services.

Parameters:

  • ctx: The parent context
  • correlationID: The correlation ID (generates one if empty)

Returns:

  • context.Context: A new context with correlation ID
  • string: The correlation ID used

func DurationContext

func DurationContext(ctx context.Context, operation string, fn func() error) (context.Context, error)

DurationContext wraps an operation and adds its duration to the context. This is useful for performance monitoring.

Parameters:

  • ctx: The parent context
  • operation: The operation name
  • fn: The function to execute

Returns:

  • context.Context: Updated context with duration
  • error: Any error from the function

Example:

ctx, err := DurationContext(ctx, "database_query", func() error {
	return db.Query(...)
})

func EnvironmentContext

func EnvironmentContext(ctx context.Context, env, version, buildID string) context.Context

EnvironmentContext adds environment information to a context. This helps distinguish logs from different environments.

Parameters:

  • ctx: The parent context
  • env: The environment name (dev, staging, prod, etc.)
  • version: The application version
  • buildID: The build/commit ID (optional)

Returns:

  • context.Context: A new context with environment information

func ErrorContext

func ErrorContext(ctx context.Context, err error) context.Context

ErrorContext adds error information to a context. This is useful for error tracking and debugging.

Parameters:

  • ctx: The parent context
  • err: The error to add

Returns:

  • context.Context: A new context with error information

func ExtractContextFields

func ExtractContextFields(ctx context.Context, keys ...ContextKey) map[string]interface{}

ExtractContextFields extracts common fields from a context. This is useful for automatically including context values in log entries.

Parameters:

  • ctx: The context to extract fields from
  • keys: The context keys to extract (if empty, extracts all common keys)

Returns:

  • map[string]interface{}: A map of extracted fields

Example:

fields := ExtractContextFields(ctx, ContextKeyRequestID, ContextKeyUserID)
logger.WithFields(fields).Info("Processing request")

func FormatContextFields

func FormatContextFields(ctx context.Context, keys ...ContextKey) string

FormatContextFields formats context fields for display. This is useful for debugging context contents.

Parameters:

  • ctx: The context to format
  • keys: The keys to include (if empty, includes all common keys)

Returns:

  • string: Formatted context fields

func LogLevelFromContext

func LogLevelFromContext(ctx context.Context, defaultLevel int) int

LogLevelFromContext extracts a log level override from context. This allows dynamic log level adjustment for specific operations.

Parameters:

  • ctx: The context to check
  • defaultLevel: The default level to use if none in context

Returns:

  • int: The log level to use

func MergeContextFields

func MergeContextFields(ctx context.Context, additionalFields map[string]interface{}, keys ...ContextKey) map[string]interface{}

MergeContextFields merges fields from a context with additional fields. Context fields take precedence over additional fields with the same key.

Parameters:

  • ctx: The context to extract fields from
  • additionalFields: Additional fields to merge
  • keys: The context keys to extract (if empty, extracts all common keys)

Returns:

  • map[string]interface{}: Merged fields map

func OperationContext

func OperationContext(ctx context.Context, component, operation string) context.Context

OperationContext creates a context for a specific operation. This helps track the flow of operations through the system.

Parameters:

  • ctx: The parent context
  • component: The component/service name
  • operation: The operation being performed

Returns:

  • context.Context: A new context with operation information

func RequestContext

func RequestContext(ctx context.Context, requestID, method, path, sourceIP string) context.Context

RequestContext creates a context with common HTTP request information. This is a convenience function for web applications.

Parameters:

  • ctx: The parent context
  • requestID: The request ID
  • method: The HTTP method
  • path: The request path
  • sourceIP: The client IP address

Returns:

  • context.Context: A new context with request information

func TraceContext

func TraceContext(ctx context.Context, traceID, spanID, parentSpanID string) context.Context

TraceContext adds tracing information to a context. This is useful for distributed tracing scenarios.

Parameters:

  • ctx: The parent context
  • traceID: The trace ID
  • spanID: The span ID
  • parentSpanID: The parent span ID (optional)

Returns:

  • context.Context: A new context with tracing information

func UserContext

func UserContext(ctx context.Context, userID, sessionID string) context.Context

UserContext adds user information to a context. This is useful for audit logging and user-specific operations.

Parameters:

  • ctx: The parent context
  • userID: The user ID
  • sessionID: The session ID (optional)

Returns:

  • context.Context: A new context with user information

func WithContextFields

func WithContextFields(ctx context.Context, fields map[ContextKey]interface{}) context.Context

WithContextFields returns a new context with the provided fields. This is useful for propagating logging context through a call chain.

Parameters:

  • ctx: The parent context
  • fields: Fields to add to the context

Returns:

  • context.Context: A new context with the fields

Example:

ctx = WithContextFields(ctx, map[ContextKey]interface{}{
	ContextKeyRequestID: "123",
	ContextKeyUserID: "456",
})

Types

type AtomicBool

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

AtomicBool provides atomic operations for bool values

func NewAtomicBool

func NewAtomicBool(initial bool) *AtomicBool

NewAtomicBool creates a new AtomicBool with the given initial value

func (*AtomicBool) CompareAndSwap

func (a *AtomicBool) CompareAndSwap(old, new bool) bool

CompareAndSwap executes the compare-and-swap operation

func (*AtomicBool) Load

func (a *AtomicBool) Load() bool

Load atomically loads and returns the value

func (*AtomicBool) Store

func (a *AtomicBool) Store(val bool)

Store atomically stores the value

func (*AtomicBool) Swap

func (a *AtomicBool) Swap(new bool) bool

Swap atomically stores new and returns the previous value

type AtomicInt64

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

AtomicInt64 provides atomic operations for int64 values

func NewAtomicInt64

func NewAtomicInt64(initial int64) *AtomicInt64

NewAtomicInt64 creates a new AtomicInt64 with the given initial value

func (*AtomicInt64) Add

func (a *AtomicInt64) Add(delta int64) int64

Add atomically adds delta to the value and returns the new value

func (*AtomicInt64) CompareAndSwap

func (a *AtomicInt64) CompareAndSwap(old, new int64) bool

CompareAndSwap executes the compare-and-swap operation

func (*AtomicInt64) Load

func (a *AtomicInt64) Load() int64

Load atomically loads and returns the value

func (*AtomicInt64) Store

func (a *AtomicInt64) Store(val int64)

Store atomically stores the value

func (*AtomicInt64) Swap

func (a *AtomicInt64) Swap(new int64) int64

Swap atomically stores new and returns the previous value

type AtomicUint64

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

AtomicUint64 provides atomic operations for uint64 values

func NewAtomicUint64

func NewAtomicUint64(initial uint64) *AtomicUint64

NewAtomicUint64 creates a new AtomicUint64 with the given initial value

func (*AtomicUint64) Add

func (a *AtomicUint64) Add(delta uint64) uint64

Add atomically adds delta to the value and returns the new value

func (*AtomicUint64) CompareAndSwap

func (a *AtomicUint64) CompareAndSwap(old, new uint64) bool

CompareAndSwap executes the compare-and-swap operation

func (*AtomicUint64) Load

func (a *AtomicUint64) Load() uint64

Load atomically loads and returns the value

func (*AtomicUint64) Store

func (a *AtomicUint64) Store(val uint64)

Store atomically stores the value

func (*AtomicUint64) Swap

func (a *AtomicUint64) Swap(new uint64) uint64

Swap atomically stores new and returns the previous value

type ContextKey

type ContextKey string

ContextKey is a type for context value keys. Using a custom type prevents collisions with other packages.

const (
	ContextKeyRequestID   ContextKey = "request_id"     // HTTP request ID for tracing
	ContextKeyTraceID     ContextKey = "trace_id"       // Distributed trace ID
	ContextKeyUserID      ContextKey = "user_id"        // User ID for audit trails
	ContextKeySessionID   ContextKey = "session_id"     // Session ID for user sessions
	ContextKeyCorrelation ContextKey = "correlation_id" // Correlation ID for event tracking
	ContextKeyComponent   ContextKey = "component"      // Component/service name
	ContextKeyOperation   ContextKey = "operation"      // Operation being performed
	ContextKeySourceIP    ContextKey = "source_ip"      // Source IP address
	ContextKeyUserAgent   ContextKey = "user_agent"     // HTTP User-Agent
	ContextKeyMethod      ContextKey = "method"         // HTTP method or RPC method
	ContextKeyPath        ContextKey = "path"           // Request path or endpoint
	ContextKeyDuration    ContextKey = "duration"       // Operation duration
	ContextKeyStatus      ContextKey = "status"         // Response status
	ContextKeyError       ContextKey = "error"          // Error information
	ContextKeySpanID      ContextKey = "span_id"        // Distributed tracing span ID
	ContextKeyParentSpan  ContextKey = "parent_span"    // Parent span ID
	ContextKeyTraceFlags  ContextKey = "trace_flags"    // Trace flags (sampled, debug, etc.)
	ContextKeyEnvironment ContextKey = "environment"    // Environment (dev, staging, prod)
	ContextKeyVersion     ContextKey = "version"        // Application/API version
	ContextKeyBuildID     ContextKey = "build_id"       // Build/commit ID
	ContextKeyTimestamp   ContextKey = "timestamp"      // Event timestamp
	ContextKeyLogLevel    ContextKey = "log_level"      // Override log level for this context
)

Common context keys for structured logging

type ContextLogger

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

ContextLogger provides context-aware logging by automatically including context fields in all log entries. It wraps an existing logger and enriches log messages with contextual information.

func NewContextLogger

func NewContextLogger(logger omni.Logger, ctx context.Context) *ContextLogger

NewContextLogger creates a new context-aware logger. This logger automatically includes context fields in all log entries.

Parameters:

  • logger: The underlying logger to wrap
  • ctx: The context to extract fields from

Returns:

  • *ContextLogger: A new context-aware logger

Example:

ctxLogger := NewContextLogger(logger, ctx)
ctxLogger.Info("Processing request") // Automatically includes context fields

func (*ContextLogger) Context

func (cl *ContextLogger) Context() context.Context

Context returns the underlying context

func (*ContextLogger) Debug

func (cl *ContextLogger) Debug(args ...interface{})

Debug logs a debug message with context fields

func (*ContextLogger) Debugf

func (cl *ContextLogger) Debugf(format string, args ...interface{})

Debugf logs a formatted debug message with context fields

func (*ContextLogger) Error

func (cl *ContextLogger) Error(args ...interface{})

Error logs an error message with context fields

func (*ContextLogger) Errorf

func (cl *ContextLogger) Errorf(format string, args ...interface{})

Errorf logs a formatted error message with context fields

func (*ContextLogger) Fields

func (cl *ContextLogger) Fields() map[string]interface{}

Fields returns the current fields

func (*ContextLogger) GetLevel

func (cl *ContextLogger) GetLevel() int

GetLevel returns the current log level

func (*ContextLogger) Info

func (cl *ContextLogger) Info(args ...interface{})

Info logs an info message with context fields

func (*ContextLogger) Infof

func (cl *ContextLogger) Infof(format string, args ...interface{})

Infof logs a formatted info message with context fields

func (*ContextLogger) IsLevelEnabled

func (cl *ContextLogger) IsLevelEnabled(level int) bool

IsLevelEnabled checks if a log level is enabled

func (*ContextLogger) Logger

func (cl *ContextLogger) Logger() omni.Logger

Logger returns the underlying logger

func (*ContextLogger) SetLevel

func (cl *ContextLogger) SetLevel(level int)

SetLevel sets the log level

func (*ContextLogger) Trace

func (cl *ContextLogger) Trace(args ...interface{})

Trace logs a trace message with context fields

func (*ContextLogger) Tracef

func (cl *ContextLogger) Tracef(format string, args ...interface{})

Tracef logs a formatted trace message with context fields

func (*ContextLogger) Warn

func (cl *ContextLogger) Warn(args ...interface{})

Warn logs a warning message with context fields

func (*ContextLogger) Warnf

func (cl *ContextLogger) Warnf(format string, args ...interface{})

Warnf logs a formatted warning message with context fields

func (*ContextLogger) WithContext

func (cl *ContextLogger) WithContext(ctx context.Context) omni.Logger

WithContext returns a new ContextLogger with an updated context. This allows changing the context while preserving the logger configuration.

Parameters:

  • ctx: The new context to use

Returns:

  • Logger: A new ContextLogger with updated context

func (*ContextLogger) WithError

func (cl *ContextLogger) WithError(err error) omni.Logger

WithError returns a new ContextLogger with an error field.

Parameters:

  • err: The error to add

Returns:

  • Logger: A new ContextLogger with error information

func (*ContextLogger) WithField

func (cl *ContextLogger) WithField(key string, value interface{}) omni.Logger

WithField returns a new ContextLogger with an additional field.

Parameters:

  • key: The field key
  • value: The field value

Returns:

  • Logger: A new ContextLogger with the added field

func (*ContextLogger) WithFields

func (cl *ContextLogger) WithFields(fields map[string]interface{}) omni.Logger

WithFields returns a new ContextLogger with additional fields. The new fields are merged with existing fields, with new fields taking precedence.

Parameters:

  • fields: Map of fields to add

Returns:

  • Logger: A new ContextLogger with merged fields

type LazyMessage

type LazyMessage struct {
	Level     int
	Format    string
	Args      []interface{}
	Timestamp time.Time
	Entry     *types.LogEntry
	Raw       []byte
	// contains filtered or unexported fields
}

LazyMessage represents a message that delays formatting until it's actually needed. This improves performance by avoiding unnecessary string formatting when messages are filtered out by log level or sampling.

func (*LazyMessage) String

func (lm *LazyMessage) String() string

String formats the message lazily. The formatting is performed only once and cached for subsequent calls. This method is thread-safe due to sync.Once.

Returns:

  • string: The formatted message

func (*LazyMessage) ToLogMessage

func (lm *LazyMessage) ToLogMessage() types.LogMessage

ToLogMessage converts a LazyMessage to a regular LogMessage. This is used when the message needs to be processed immediately.

Returns:

  • LogMessage: A regular log message with the same content

Jump to

Keyboard shortcuts

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