core

package
v0.0.0-...-0a1c337 Latest Latest
Warning

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

Go to latest
Published: May 20, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package core provides internal implementation utilities for LOXA-Go. These types are not part of the public API.

Index

Constants

View Source
const (
	// CanonicalWins keeps the canonical value and silently drops the attr (default).
	CanonicalWins DuplicateFieldPolicy = iota
	// AttrWins overwrites the canonical field with the attr value.
	AttrWins
	// KeepBothUnderAttrs keeps the canonical value and moves the conflicting
	// attr under an "attrs" key.
	KeepBothUnderAttrs
	// DropDuplicateAttr silently drops the attr (same as CanonicalWins).
	DropDuplicateAttr
	// ErrorOnDuplicate returns an error when a custom attr conflicts with a canonical field.
	ErrorOnDuplicate

	// KeepBoth is alias for KeepBothUnderAttrs.
	KeepBoth = KeepBothUnderAttrs
	// UserWins lets user attrs overwrite canonical fields when possible.
	UserWins = AttrWins
	// AttrsWin lets attrs overwrite canonical fields when possible.
	AttrsWin = AttrWins
	// FirstWins keeps the first canonical value for duplicate canonical attrs.
	FirstWins = CanonicalWins
	// LastWins lets the latest duplicate attr overwrite canonical fields when possible.
	LastWins = AttrWins
)
View Source
const (
	LOXA_SPEC_VERSION       = speccontract.LOXASpecVersion
	LOXA_INGEST_API_VERSION = speccontract.LOXAIngestAPIVersion
	LOXA_EVENT_VERSION      = speccontract.LOXAEventVersion
)

Variables

View Source
var CanonicalFieldSet = speccontract.CanonicalFieldSet

CanonicalFieldSet is the generated set of top-level canonical JSON field names.

View Source
var ErrConfigFileNotFound = errors.New("loxa: config file not found")

ErrConfigFileNotFound is returned when no config file is found.

View Source
var ErrInvalidConfig = errors.New("loxa: invalid config")

ErrInvalidConfig is returned when configuration validation fails.

View Source
var ErrPipelineClosed = errors.New("pipeline closed")

ErrPipelineClosed is returned when enqueueing after shutdown starts.

Functions

func AssertEvent

func AssertEvent(t testing.TB, ev *Event, key string, expected any)

AssertEvent asserts a key on event attrs equals expected.

func Configure

func Configure(cfg Config) error

Configure replaces the global default logger with a new one built from cfg. The previous default logger is drained/shutdown to avoid losing queued events.

func EventID

func EventID(ctx context.Context) string

EventID returns the event id from ctx when present.

func GenerateSpanID

func GenerateSpanID() string

GenerateSpanID generates a new W3C Trace Context span-id (16 hex characters, 8 bytes). Format: 16 lowercase hex characters representing an 8-byte array. Example: "00f067aa0ba902b7" Requirements: 39.6

func GenerateTraceID

func GenerateTraceID() string

GenerateTraceID generates a new W3C Trace Context trace-id (32 hex characters, 16 bytes). Format: 32 lowercase hex characters representing a 16-byte array. Example: "0af7651916cd43dd8448eb211c80319c" Requirements: 39.6

func HasEvent

func HasEvent(ctx context.Context) bool

HasEvent reports if ctx has an active canonical event.

func InjectHTTPHeaderCarrier

func InjectHTTPHeaderCarrier(ctx context.Context, header http.Header) http.Header

InjectHTTPHeaderCarrier injects LOXA and trace context into headers.

func InjectHTTPHeaders

func InjectHTTPHeaders(req *http.Request)

InjectHTTPHeaders injects LOXA + trace context headers into an outbound request.

func IsCanonical

func IsCanonical(key string) bool

IsCanonical returns true if key matches a canonical field name.

func IsValidSpanID

func IsValidSpanID(spanID string) bool

IsValidSpanID checks if a span ID is valid according to W3C Trace Context spec. Valid span IDs are 16 hex characters and not all zeros.

func IsValidTraceID

func IsValidTraceID(traceID string) bool

IsValidTraceID checks if a trace ID is valid according to W3C Trace Context spec. Valid trace IDs are 32 hex characters and not all zeros.

func MemorySink

func MemorySink() (Sink, *MemorySinkStore)

func NewEventMap

func NewEventMap(in BuildInput) map[string]any

NewEventMap builds a canonical map representation used by optional internal paths.

func NewRoundTripper

func NewRoundTripper(base http.RoundTripper) http.RoundTripper

NewRoundTripper wraps a base transport and enriches active events with outbound HTTP metadata.

func NewUUIDv7

func NewUUIDv7() string

NewUUIDv7 generates a new UUIDv7 string using the global generator. IDs are monotonically increasing within the same millisecond.

func PanicRecoveryEnabled

func PanicRecoveryEnabled() bool

PanicRecoveryEnabled reports whether the default logger recovers panics in wrappers.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request id from ctx when present.

func RequestIDFromHTTP

func RequestIDFromHTTP(r *http.Request) string

RequestIDFromHTTP resolves request id from header, then active event context.

func RunCLI

func RunCLI(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunCLI wraps an operation in a CLI canonical event lifecycle.

func RunCron

func RunCron(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunCron wraps an operation in a cron canonical event lifecycle.

func RunEvent

func RunEvent(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunEvent wraps an operation in the canonical lifecycle: StartEvent -> fn -> Finish/FinishError -> Emit.

func RunHTTP

func RunHTTP(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunHTTP wraps an operation in an HTTP canonical event lifecycle.

func RunJob

func RunJob(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunJob wraps an operation in a job canonical event lifecycle.

func RunQueue

func RunQueue(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error

RunQueue wraps an operation in a queue canonical event lifecycle.

func SetDefault

func SetDefault(l *Logger)

SetDefault replaces the global default logger instance.

func SpanIDFromContext

func SpanIDFromContext(ctx context.Context) string

SpanIDFromContext returns the span id from ctx when present.

func TestLogger

func TestLogger() (*Logger, *MemorySinkStore, error)

TestLogger creates a logger configured for tests plus its backing memory store.

func TraceFromOTel

func TraceFromOTel(ctx context.Context) (traceID string, spanID string)

TraceFromOTel returns trace and span ids from the current OTel span context.

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext returns the trace id from ctx when present.

func ValidateIngestEnvelopeBytes

func ValidateIngestEnvelopeBytes(raw []byte, strict bool) error

ValidateIngestEnvelopeBytes validates a runtime envelope payload against the generated contract before it is sent to the collector.

func WrapHTTPClient

func WrapHTTPClient(client *http.Client) *http.Client

WrapHTTPClient wraps an existing client with LOXA outbound instrumentation.

Types

type AsyncConfig

type AsyncConfig struct {
	// Enabled turns on async mode. Default: true in Production(), false in Dev().
	Enabled bool
	// QueueSize is the channel depth. Default: 8192.
	QueueSize int
	// Workers is the number of goroutines draining the queue. Default: 4.
	Workers int
	// FlushInterval is how often buffered sinks are flushed. Default: 1s.
	FlushInterval time.Duration
	// MaxBatchBytes caps the byte size of each sink batch. Default: 4MB.
	MaxBatchBytes int
	// Backpressure controls what happens when the queue is full. Default: Block.
	Backpressure BackpressurePolicy
}

AsyncConfig configures the background async emit pipeline.

type Attr

type Attr struct {
	Key   string
	Kind  Kind
	Value any
}

Attr is a typed key-value pair used to enrich canonical events. Canonical fields use Kind to skip reflection on the fast path.

func Amount

func Amount(value int64) Attr

Amount sets payment.amount.

func Any

func Any(key string, val any) Attr

Any creates an Attr whose value is encoded via encoding/json (slow path).

func AppVersion

func AppVersion(value string) Attr

AppVersion sets app.version.

func Attempt

func Attempt(n int) Attr

Attempt sets retry.attempt.

func Bool

func Bool(key string, val bool) Attr

Bool creates a bool Attr.

func CartID

func CartID(id string) Attr

CartID sets cart.id.

func CartTotalCents

func CartTotalCents(total int64) Attr

CartTotalCents sets cart.total_cents.

func Country

func Country(code string) Attr

Country sets geo.country.

func Currency

func Currency(code string) Attr

Currency sets payment.currency.

func CustomerID

func CustomerID(id string) Attr

CustomerID sets customer.id.

func DeploymentID

func DeploymentID(id string) Attr

DeploymentID sets the canonical deployment_id field.

func Device

func Device(value string) Attr

Device sets device.name.

func Duration

func Duration(key string, val time.Duration) Attr

Duration creates a time.Duration Attr (encoded as float64 milliseconds).

func DurationMS

func DurationMS(ms int64) Attr

DurationMS sets the canonical duration_ms field.

func Err

func Err(err error) Attr

Err creates an error Attr under the key "error". If err is nil the Attr is zero-valued.

func ErrorCode

func ErrorCode(code string) Attr

ErrorCode sets error.code.

func ErrorMessage

func ErrorMessage(msg string) Attr

ErrorMessage sets error.message.

func ErrorStack

func ErrorStack(stack string) Attr

ErrorStack sets error.stack.

func ErrorType

func ErrorType(name string) Attr

ErrorType sets error.type.

func Experiment

func Experiment(name, variant string) Attr

Experiment adds an experiment variant field.

func ExtractHTTPHeaderAttrs

func ExtractHTTPHeaderAttrs(header http.Header) []Attr

ExtractHTTPHeaderAttrs converts common tracing/request headers into attrs.

func ExtractHTTPHeaderAttrsWithContext

func ExtractHTTPHeaderAttrsWithContext(ctx context.Context, header http.Header) []Attr

ExtractHTTPHeaderAttrsWithContext converts common tracing/request headers into attrs.

func ExtractHTTPHeaders

func ExtractHTTPHeaders(r *http.Request) []Attr

ExtractHTTPHeaders converts common tracing/request headers into attrs.

func FeatureFlag

func FeatureFlag(name string, value any) Attr

FeatureFlag adds a feature flag entry under the feature group.

func FeatureFlagBool

func FeatureFlagBool(name string, enabled bool) Attr

FeatureFlagBool adds a boolean feature flag.

func Float64

func Float64(key string, val float64) Attr

Float64 creates a float64 Attr.

func Group

func Group(key string, attrs ...Attr) Attr

Group creates a nested object Attr.

loxa.Group("user", loxa.String("id", uid), loxa.String("plan", "pro"))
→ {"user":{"id":"...","plan":"pro"}}

func HashString

func HashString(key, value string) Attr

HashString stores a hash-ready marker field for sensitive values.

func Int

func Int(key string, val int) Attr

Int creates an int Attr.

func Int64

func Int64(key string, val int64) Attr

Int64 creates an int64 Attr.

func JobName

func JobName(name string) Attr

JobName sets job.name.

func MarkSensitive

func MarkSensitive(attr Attr) Attr

MarkSensitive marks attr key as sensitive metadata.

func MessageID

func MessageID(id string) Attr

MessageID sets message.id.

func Method

func Method(method string) Attr

Method sets the canonical method field.

func Null

func Null(key string) Attr

Null creates an Attr with a null JSON value.

func OrderID

func OrderID(id string) Attr

OrderID sets order.id.

func OrganizationID

func OrganizationID(id string) Attr

OrganizationID sets organization.id.

func Outcome

func Outcome(outcome string) Attr

Outcome sets the canonical outcome field.

func Path

func Path(path string) Attr

Path sets the canonical path field.

func PaymentLatencyMS

func PaymentLatencyMS(ms int64) Attr

PaymentLatencyMS sets payment.latency_ms.

func PaymentProvider

func PaymentProvider(provider string) Attr

PaymentProvider sets payment.provider.

func Plan

func Plan(name string) Attr

Plan sets customer.plan.

func Platform

func Platform(value string) Attr

Platform sets device.platform.

func ProductID

func ProductID(id string) Attr

ProductID sets product.id.

func QueueName

func QueueName(name string) Attr

QueueName sets queue.name.

func Region

func Region(region string) Attr

Region sets the canonical region field.

func RequestID

func RequestID(id string) Attr

RequestID sets the canonical request_id field.

func Retryable

func Retryable(v bool) Attr

Retryable sets error.retryable.

func Route

func Route(route string) Attr

Route sets the canonical route field.

func SensitiveString

func SensitiveString(key, value string) Attr

SensitiveString marks a string field as sensitive.

func Service

func Service(service string) Attr

Service sets the canonical service field.

func SessionID

func SessionID(id string) Attr

SessionID sets session.id.

func SpanID

func SpanID(id string) Attr

SpanID sets the canonical span_id field.

func StatusCode

func StatusCode(code int) Attr

StatusCode sets the canonical status_code field.

func String

func String(key, val string) Attr

String creates a string Attr.

func Stringer

func Stringer(key string, val fmt.Stringer) Attr

Stringer creates an Attr from any value implementing fmt.Stringer.

func TenantID

func TenantID(id string) Attr

TenantID sets tenant.id.

func Time

func Time(key string, val time.Time) Attr

Time creates a time.Time Attr (encoded as RFC3339Nano).

func TraceID

func TraceID(id string) Attr

TraceID sets the canonical trace_id field.

func Uint64

func Uint64(key string, val uint64) Attr

Uint64 creates a uint64 Attr.

func UserID

func UserID(id string) Attr

UserID sets user.id as a dot-key attr (expanded to {"user":{"id":...}}).

func UserSubscription

func UserSubscription(sub string) Attr

UserSubscription sets user.subscription.

func Version

func Version(version string) Attr

Version sets the canonical version field.

func WorkspaceID

func WorkspaceID(id string) Attr

WorkspaceID sets workspace.id.

type BackpressurePolicy

type BackpressurePolicy int

BackpressurePolicy determines what happens when the async queue is full.

const (
	// Block waits until space is available (default — protects against data loss).
	Block BackpressurePolicy = iota
	// DropNewest drops the incoming event when the queue is full.
	DropNewest
	// DropOldest discards the oldest queued event to make room.
	DropOldest
	// DropDebug drops debug-level events first under pressure.
	DropDebug
	// DropSampled drops sampled (non-error) events first.
	DropSampled
	// SyncFallback writes synchronously to sinks if the queue is full.
	SyncFallback
)

type BatchSinkWriter

type BatchSinkWriter interface {
	WriteBatch(ctx context.Context, items []PipelineItem) error
}

BatchSinkWriter optionally accepts a batch of pipeline items in one call.

type BuildInput

type BuildInput struct {
	Timestamp   time.Time
	EventID     string
	RequestID   string
	TraceID     string
	SpanID      string
	ParentID    string
	Level       string
	Event       string
	Message     string
	Outcome     string
	Service     string
	Version     string
	Environment string
	Method      string
	Path        string
	Route       string
	StatusCode  int
	DurationMS  int64
}

BuildInput contains normalized values used to construct a canonical event map.

type CheckpointConfig

type CheckpointConfig struct {
	// Enabled allows checkpoints to be recorded. Default: true.
	Enabled bool
	// EmitImmediately emits each checkpoint as a standalone log line in
	// addition to including it in the final event. Default: false.
	EmitImmediately bool
	// MaxCheckpoints caps how many checkpoints are stored per event. Default: 32.
	MaxCheckpoints int
}

CheckpointConfig controls checkpoint behaviour.

type Clock

type Clock interface {
	Now() time.Time
}

Clock abstracts time to allow deterministic testing.

func NewMockClock

func NewMockClock(t time.Time) Clock

NewMockClock returns a Clock that always returns t.

type CodedError

type CodedError interface {
	Code() string
}

CodedError is implemented by errors that carry a machine-readable code.

type CollectorSinkConfig

type CollectorSinkConfig struct {
	Endpoint          string
	Headers           map[string]string
	Client            *http.Client
	Transport         *HTTPTransport
	Metrics           *MetricsCollector
	MaxRetries        int
	MaxBackoff        time.Duration
	Timeout           time.Duration
	ConnectionTimeout time.Duration
	SDKName           string
	SDKVersion        string
	Service           string
	EnableCompression bool
}

CollectorSinkConfig configures the lightweight HTTP batch collector sink.

type Config

type Config struct {
	// ── Service identity ──────────────────────────────────────────────────────
	Service      string
	Version      string
	Environment  string
	DeploymentID string
	Region       string
	TenantID     string // Multi-tenant identifier

	// ── Collector configuration ───────────────────────────────────────────────
	CollectorURL string // URL of the LOXA collector (required)

	// ── Batching configuration ────────────────────────────────────────────────
	BatchSize     int           // Number of events per batch (default: 100)
	FlushInterval time.Duration // Time between automatic flushes (default: 5s)
	MaxBufferSize int           // Maximum events in buffer before dropping (default: 10000)

	// ── Retry configuration ───────────────────────────────────────────────────
	MaxRetries        int           // Maximum retry attempts (default: 3)
	MaxBackoff        time.Duration // Maximum backoff duration (default: 30s)
	Timeout           time.Duration // Request timeout (default: 10s)
	ConnectionTimeout time.Duration // Connection timeout (default: 5s)

	// ── Compression ───────────────────────────────────────────────────────────
	EnableCompression bool // Enable gzip compression for HTTP requests (default: true)

	// ── Log level ─────────────────────────────────────────────────────────────
	// Events below Level are dropped before encoding. Default: LevelInfo.
	Level Level

	// ── Pipeline components ───────────────────────────────────────────────────
	Sampler           Sampler
	Encoder           Encoder
	Schema            Schema
	Sink              Sink
	Sinks             []Sink
	Redactor          Redactor
	ErrorExtractor    ErrorExtractor
	Enricher          ContextEnricher
	FallbackSink      Sink
	StatsHandler      StatsHandler
	CollectorEndpoint string // Deprecated: use CollectorURL instead

	// ── Optional metadata ─────────────────────────────────────────────────────
	IncludeHost    bool // include os.Hostname() in every event
	IncludeRuntime bool // include Go runtime version
	IncludeSource  bool // include caller file:line and default error stacks (expensive)

	// ── Subsystem configs ─────────────────────────────────────────────────────
	Async                AsyncConfig
	FieldNaming          FieldNamingConfig
	DuplicateFieldPolicy DuplicateFieldPolicy
	Checkpoints          CheckpointConfig
	PanicRecovery        bool
	Security             SecurityConfig
	// Strict enables stronger runtime validation for event shape and attrs.
	Strict bool

	// ── ID generation ─────────────────────────────────────────────────────────
	IDGen IDGenerator

	// ── Clock ─────────────────────────────────────────────────────────────────
	Clock Clock
	// contains filtered or unexported fields
}

Config is the top-level LOXA-Go configuration.

func ApplyConfig

func ApplyConfig(cfg Config, options ...ConfigOption) Config

ApplyConfig applies options to cfg in order.

func Dev

func Dev() Config

Dev returns a config suitable for local development: pretty-print JSON, stdout, sync, no sampling, debug level.

func LoadFromEnv

func LoadFromEnv(base Config) Config

LoadFromEnv loads configuration from environment variables and applies them to the provided config. Environment variables take precedence over the base config but are overridden by explicit code configuration.

Supported environment variables:

  • LOXA_COLLECTOR_URL: Collector endpoint URL
  • LOXA_SERVICE_NAME: Service name
  • LOXA_SERVICE_VERSION: Service version
  • LOXA_ENVIRONMENT: Deployment environment
  • LOXA_TENANT_ID: Tenant identifier
  • LOXA_BATCH_SIZE: Batch size for event buffering (integer)
  • LOXA_FLUSH_INTERVAL: Flush interval duration (e.g., "5s")
  • LOXA_MAX_BUFFER_SIZE: Maximum buffer size (integer)
  • LOXA_MAX_RETRIES: Maximum retry attempts (integer)
  • LOXA_MAX_BACKOFF: Maximum backoff duration (e.g., "30s")
  • LOXA_TIMEOUT: Request timeout (e.g., "10s")
  • LOXA_CONNECTION_TIMEOUT: Connection timeout (e.g., "5s")
  • LOXA_ENABLE_COMPRESSION: Enable compression ("true" or "false")

func Production

func Production() Config

Production returns a config suitable for production: compact JSON, stdout, async, sample errors + slow requests, info level.

func Test

func Test() Config

Test returns a config suitable for unit tests: sync, no sinks, debug level.

func (Config) Validate

func (c Config) Validate() error

Validate validates cfg and returns explicit field-level errors. In strict mode, additional config checks are enforced.

func (Config) WithAllowPII

func (c Config) WithAllowPII(allow bool) Config

WithAllowPII enables or disables PII exposure when RedactByDefault is true.

func (Config) WithAsync

func (c Config) WithAsync(enabled bool) Config

WithAsync enables or disables async mode.

func (Config) WithAsyncFlushInterval

func (c Config) WithAsyncFlushInterval(interval time.Duration) Config

WithAsyncFlushInterval sets async flush interval and enables async mode.

func (Config) WithAsyncMaxBatchBytes

func (c Config) WithAsyncMaxBatchBytes(maxBytes int) Config

WithAsyncMaxBatchBytes sets async max batch size and enables async mode.

func (Config) WithAsyncQueue

func (c Config) WithAsyncQueue(size int) Config

WithAsyncQueue sets async queue size and enables async mode.

func (Config) WithBackpressure

func (c Config) WithBackpressure(policy BackpressurePolicy) Config

WithBackpressure sets async backpressure policy.

func (Config) WithCollectorEndpoint

func (c Config) WithCollectorEndpoint(endpoint string) Config

func (Config) WithCompression

func (c Config) WithCompression(enabled bool) Config

WithCompression enables or disables gzip compression for collector requests.

func (Config) WithDropOversizedEvents

func (c Config) WithDropOversizedEvents(drop bool) Config

WithDropOversizedEvents enables or disables dropping of events that exceed max_event_bytes.

func (Config) WithDuplicatePolicy

func (c Config) WithDuplicatePolicy(policy DuplicateFieldPolicy) Config

WithDuplicatePolicy sets duplicate field conflict policy.

func (Config) WithEncoder

func (c Config) WithEncoder(e Encoder) Config

WithEncoder sets the encoder.

func (Config) WithEnricher

func (c Config) WithEnricher(fn ContextEnricher) Config

WithEnricher sets a context enricher hook that runs during Emit(ctx).

func (Config) WithEnvironment

func (c Config) WithEnvironment(environment string) Config

WithEnvironment returns a copy of cfg with Environment set.

func (Config) WithEventSchema

func (c Config) WithEventSchema(schema Schema) Config

WithEventSchema sets the output event schema.

func (Config) WithFallbackSink

func (c Config) WithFallbackSink(sink Sink) Config

WithFallbackSink configures a sink used when primary sink writes fail.

func (Config) WithMaxAttrCount

func (c Config) WithMaxAttrCount(max int) Config

WithMaxAttrCount sets the maximum number of attributes per event.

func (Config) WithMaxEventBytes

func (c Config) WithMaxEventBytes(max int) Config

WithMaxEventBytes sets the maximum byte size for entire events.

func (Config) WithMaxFieldBytes

func (c Config) WithMaxFieldBytes(max int) Config

WithMaxFieldBytes sets the maximum byte size for individual field values.

func (Config) WithRedactByDefault

func (c Config) WithRedactByDefault(redact bool) Config

WithRedactByDefault enables or disables redaction of sensitive fields by default.

func (Config) WithRedactor

func (c Config) WithRedactor(r Redactor) Config

WithRedactor sets the redactor.

func (Config) WithSampler

func (c Config) WithSampler(s Sampler) Config

WithSampler sets the sampler.

func (Config) WithSchema

func (c Config) WithSchema(schema Schema) Config

WithSchema sets the output event schema.

func (Config) WithService

func (c Config) WithService(service string) Config

WithService returns a copy of cfg with Service set.

func (Config) WithSink

func (c Config) WithSink(sink Sink) Config

WithSink appends a sink.

func (Config) WithStatsHandler

func (c Config) WithStatsHandler(handler StatsHandler) Config

WithStatsHandler sets callbacks for emit/drop/error telemetry.

func (Config) WithStrict

func (c Config) WithStrict(strict bool) Config

WithStrict enables or disables strict mode validation.

func (Config) WithVersion

func (c Config) WithVersion(version string) Config

WithVersion returns a copy of cfg with Version set.

func (Config) WithWorkers

func (c Config) WithWorkers(workers int) Config

WithWorkers sets async worker count and enables async mode.

type ConfigOption

type ConfigOption func(Config) Config

ConfigOption mutates and returns a Config.

func WithAsync

func WithAsync(enabled bool) ConfigOption

WithAsync applies async enabled state.

func WithAsyncFlushInterval

func WithAsyncFlushInterval(interval time.Duration) ConfigOption

WithAsyncFlushInterval applies async flush interval.

func WithAsyncMaxBatchBytes

func WithAsyncMaxBatchBytes(maxBytes int) ConfigOption

WithAsyncMaxBatchBytes applies async max batch size.

func WithAsyncQueue

func WithAsyncQueue(size int) ConfigOption

WithAsyncQueue applies async queue size.

func WithBackpressure

func WithBackpressure(policy BackpressurePolicy) ConfigOption

WithBackpressure applies backpressure policy.

func WithBatchSize

func WithBatchSize(size int) ConfigOption

WithBatchSize applies the batch size.

func WithCollectorEndpoint

func WithCollectorEndpoint(endpoint string) ConfigOption

WithCollectorEndpoint applies the default collector endpoint.

func WithCollectorURL

func WithCollectorURL(url string) ConfigOption

WithCollectorURL applies the collector URL.

func WithCompression

func WithCompression(enabled bool) ConfigOption

WithCompression applies the compression setting.

func WithConnectionTimeout

func WithConnectionTimeout(timeout time.Duration) ConfigOption

WithConnectionTimeout applies the connection timeout.

func WithDuplicatePolicy

func WithDuplicatePolicy(policy DuplicateFieldPolicy) ConfigOption

WithDuplicatePolicy applies duplicate field policy.

func WithEncoder

func WithEncoder(encoder Encoder) ConfigOption

WithEncoder applies encoder.

func WithEnricher

func WithEnricher(enricher ContextEnricher) ConfigOption

WithEnricher applies context enricher.

func WithEnvironment

func WithEnvironment(environment string) ConfigOption

WithEnvironment applies environment.

func WithEventSchema

func WithEventSchema(schema Schema) ConfigOption

WithEventSchema applies event schema.

func WithFallbackSink

func WithFallbackSink(sink Sink) ConfigOption

WithFallbackSink applies fallback sink.

func WithFlushInterval

func WithFlushInterval(interval time.Duration) ConfigOption

WithFlushInterval applies the flush interval.

func WithMaxBackoff

func WithMaxBackoff(backoff time.Duration) ConfigOption

WithMaxBackoff applies the maximum backoff duration.

func WithMaxBufferSize

func WithMaxBufferSize(size int) ConfigOption

WithMaxBufferSize applies the maximum buffer size.

func WithMaxRetries

func WithMaxRetries(retries int) ConfigOption

WithMaxRetries applies the maximum retry attempts.

func WithRedactor

func WithRedactor(redactor Redactor) ConfigOption

WithRedactor applies redactor.

func WithSampler

func WithSampler(sampler Sampler) ConfigOption

WithSampler applies sampler.

func WithSchema

func WithSchema(schema Schema) ConfigOption

WithSchema applies event schema.

func WithService

func WithService(service string) ConfigOption

WithService applies service name.

func WithSink

func WithSink(sink Sink) ConfigOption

WithSink applies sink.

func WithStatsHandler

func WithStatsHandler(handler StatsHandler) ConfigOption

WithStatsHandler applies stats handler callbacks.

func WithStrict

func WithStrict(strict bool) ConfigOption

WithStrict applies strict mode.

func WithTenantID

func WithTenantID(tenantID string) ConfigOption

WithTenantID applies the tenant ID.

func WithTimeout

func WithTimeout(timeout time.Duration) ConfigOption

WithTimeout applies the request timeout.

func WithVersion

func WithVersion(version string) ConfigOption

WithVersion applies version.

func WithWorkers

func WithWorkers(workers int) ConfigOption

WithWorkers applies async worker count.

type ConfigValidationError

type ConfigValidationError struct {
	Field   string
	Problem string
}

ConfigValidationError is returned when a specific config field is invalid.

func (*ConfigValidationError) Error

func (e *ConfigValidationError) Error() string

func (*ConfigValidationError) Unwrap

func (e *ConfigValidationError) Unwrap() error

type ContextEnricher

type ContextEnricher func(ctx context.Context) []Attr

ContextEnricher appends attrs derived from request/job context during Emit.

type DeliveryFailureHandler

type DeliveryFailureHandler interface {
	OnDeliveryFailed(ev *Event, err error)
}

DeliveryFailureHandler is an optional extension for StatsHandler implementations that want explicit delivery-failure callbacks.

type DotNode

type DotNode struct {
	// Value holds the leaf attr value (Kind, Value) when Children is nil.
	Value *LeafValue
	// Children maps sub-key → child node.
	Children map[string]*DotNode
}

DotNode is an intermediate tree node used to merge dot-key attrs (e.g. "user.id", "user.name") into nested JSON objects.

func ExpandDotKeys

func ExpandDotKeys(keys []string, kinds []uint8, values []any) (
	plainKeys []string, plainKinds []uint8, plainValues []any,
	groupKeys []string, groupRoots []*DotNode,
)

ExpandDotKeys takes a flat list of (key, kind, value) tuples and converts all dot-separated keys into a nested tree. Non-dot keys are left as-is.

Returns two slices:

  • plain: attrs whose keys have no dot (or dot expansion is disabled)
  • groups: map[topKey]*DotNode for merged nested objects

type DuplicateEmitError

type DuplicateEmitError struct {
	EventID string
}

DuplicateEmitError is returned when Emit is called after an event has already reached the emitted terminal state.

func (*DuplicateEmitError) Error

func (e *DuplicateEmitError) Error() string

type DuplicateFieldError

type DuplicateFieldError struct {
	Key string
}

DuplicateFieldError is returned when duplicate canonical attrs are rejected by DuplicateFieldPolicy=ErrorOnDuplicate.

func (*DuplicateFieldError) Error

func (e *DuplicateFieldError) Error() string

type DuplicateFieldPolicy

type DuplicateFieldPolicy int

DuplicateFieldPolicy controls what happens when a custom Attr has the same key as a canonical field (e.g. loxa.String("service", "x") when service is already set from Params).

type Encoder

type Encoder interface {
	EncodeEvent(dst []byte, ev *Event) ([]byte, error)
}

Encoder converts an Event to its wire representation.

type ErrorExtractor

type ErrorExtractor func(err error) *ErrorInfo

ErrorExtractor converts an error into an ErrorInfo. Override this on Config to customise extraction (e.g. for pkg/errors).

type ErrorInfo

type ErrorInfo struct {
	Type      string `json:"type"`
	Code      string `json:"code,omitempty"`
	Message   string `json:"message"`
	Retriable bool   `json:"retriable,omitempty"`
	Stack     string `json:"stack,omitempty"`
	Cause     string `json:"cause,omitempty"`
}

ErrorInfo is the structured representation of an error attached to an event.

func DefaultErrorExtractor

func DefaultErrorExtractor(err error) *ErrorInfo

DefaultErrorExtractor is the built-in extractor used when none is configured.

func DefaultErrorExtractorNoStack

func DefaultErrorExtractorNoStack(err error) *ErrorInfo

DefaultErrorExtractorNoStack is equivalent to DefaultErrorExtractor but omits stack traces.

type Event

type Event struct {

	// ── Correlation IDs ──────────────────────────────────────────────────────
	Timestamp     time.Time
	SchemaVersion string
	EventVersion  string
	EventID       string
	RequestID     string
	TraceID       string
	SpanID        string
	ParentID      string

	// ── Classification ───────────────────────────────────────────────────────
	Level   Level
	Event   string
	Kind    string
	Message string
	Outcome string

	// ── Service metadata ─────────────────────────────────────────────────────
	Service      string
	Version      string
	Environment  string
	DeploymentID string
	Region       string
	Host         string
	Runtime      string

	// ── Request metadata ─────────────────────────────────────────────────────
	Method     string
	Path       string
	Route      string
	StatusCode int
	DurationMS int64

	// ── Timing ───────────────────────────────────────────────────────────────
	StartedAt  time.Time
	FinishedAt time.Time

	// ── Custom context ───────────────────────────────────────────────────────
	Attrs       []Attr
	Checkpoints []EventCheckpoint
	Error       *ErrorInfo
	// contains filtered or unexported fields
}

Event is the canonical wide event built for one request, job, or service hop. Canonical fields are typed struct members — encoded without reflection. Custom business context lives in Attrs. All methods are safe for concurrent use.

func Capture

func Capture(fn func()) ([]*Event, error)

Capture runs fn with a temporary memory sink and returns captured events.

func FromContext

func FromContext(ctx context.Context) (*Event, bool)

FromContext retrieves the canonical Event from ctx. Returns (nil, false) if StartEvent has not been called.

func NewEvent

func NewEvent(params Params) *Event

NewEvent creates a manual event instance without storing it in context.

func (*Event) Add

func (e *Event) Add(key string, value interface{}) error

Add appends a value to an array field on an active event. If the field doesn't exist, it creates a new array with the value. If the field exists but is not an array, it returns an error. Requirements: 2.4

func (*Event) AddAttrs

func (e *Event) AddAttrs(attrs []Attr) error

AddAttrs appends attrs to the event under the mutex.

func (*Event) AddCheckpoint

func (e *Event) AddCheckpoint(cp EventCheckpoint) error

AddCheckpoint appends an EventCheckpoint under the mutex.

func (*Event) Append

func (e *Event) Append(attrs ...Attr) error

Append appends attrs to this event.

func (*Event) AttrList

func (e *Event) AttrList() []Attr

AttrList returns a copy of event attrs.

func (*Event) Checkpoint

func (e *Event) Checkpoint(name string, attrs ...Attr) error

Checkpoint records a checkpoint on this event.

func (*Event) Clone

func (e *Event) Clone() *Event

Clone returns a deep copy of the event with emitted state reset.

func (*Event) Delete

func (e *Event) Delete(keys ...string) error

Delete removes attrs by key. Dot keys can target group children (e.g. "user.id").

func (*Event) Duration

func (e *Event) Duration() time.Duration

Duration returns event duration.

func (*Event) Emit

func (e *Event) Emit() error

Emit emits this event using its logger (or the default logger).

func (*Event) Enrich

func (e *Event) Enrich(attrs ...Attr) error

Enrich appends attrs to this event. Requirements: 1.3, 2.2

func (*Event) Finish

func (e *Event) Finish(outcome string, attrs ...Attr) error

Finish records a successful/completed outcome on this event.

func (*Event) FinishError

func (e *Event) FinishError(err error, attrs ...Attr) error

FinishError marks this event as failed.

func (*Event) Flush

func (e *Event) Flush(ctx context.Context) error

Flush flushes sinks for this event's logger.

func (*Event) Get

func (e *Event) Get(key string) (any, bool)

Get returns a value by key. Dot paths are supported.

func (*Event) GetGroup

func (e *Event) GetGroup(name string) (map[string]any, bool)

GetGroup returns a group as map by group key.

func (*Event) ID

func (e *Event) ID() string

ID returns event id.

func (*Event) IsEmitted

func (e *Event) IsEmitted() bool

IsEmitted reports if event has been emitted.

func (*Event) IsFinished

func (e *Event) IsFinished() bool

IsFinished reports if event finish timestamp is set.

func (*Event) MarkEmitted

func (e *Event) MarkEmitted() bool

MarkEmitted is kept for compatibility with older tests and helper code. New emit paths should use beginEmit/markEmitted so validation failures do not burn the emitted state.

func (*Event) Merge

func (e *Event) Merge(group string, attrs ...Attr) error

Merge merges attrs into a named group.

func (*Event) MuLock

func (e *Event) MuLock()

MuLock acquires the event mutex. Use sparingly; prefer the accessor methods.

func (*Event) MuUnlock

func (e *Event) MuUnlock()

MuUnlock releases the event mutex.

func (*Event) Request

func (e *Event) Request() string

Request returns request id.

func (*Event) Set

func (e *Event) Set(attrs ...Attr) error

Set upserts attrs by key and applies canonical fields when keys match. Requirements: 1.3, 2.3

func (*Event) SetError

func (e *Event) SetError(info *ErrorInfo)

SetError sets the ErrorInfo field (used by immediate logger).

func (*Event) SetLogger

func (e *Event) SetLogger(l *Logger)

SetLogger binds the Logger that owns this event (used by logger.go).

func (*Event) SetOutcome

func (e *Event) SetOutcome(outcome string)

SetOutcome sets the Outcome field.

func (*Event) StartTime

func (e *Event) StartTime() time.Time

StartTime returns start time.

func (*Event) State

func (e *Event) State() EventState

State returns the current event state for observability. Requirements: 1.10

func (*Event) String

func (e *Event) String() string

func (*Event) Trace

func (e *Event) Trace() string

Trace returns trace id.

type EventAlreadyFinishedError

type EventAlreadyFinishedError struct {
	EventID string
}

EventAlreadyFinishedError is returned when Finish or FinishError is called more than once before emit.

func (*EventAlreadyFinishedError) Error

func (e *EventAlreadyFinishedError) Error() string

type EventBuffer

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

EventBuffer is an in-memory buffer for events with automatic flushing. It implements batching and buffering per Requirement 33.

Requirements: 33.1, 33.2, 33.3, 33.4, 33.5, 33.6, 33.7, 33.8, 33.9, 33.10, 33.11

func NewEventBuffer

func NewEventBuffer(cfg EventBufferConfig) *EventBuffer

NewEventBuffer creates a new event buffer with the given configuration. Requirement 33.1

func (*EventBuffer) Add

func (b *EventBuffer) Add(ctx context.Context, ev *Event, encoded []byte) error

Add adds an event to the buffer. If the buffer reaches batch_size, it flushes automatically. If the buffer exceeds max_buffer_size, oldest events are dropped. Requirements: 33.4, 33.8, 33.9

func (*EventBuffer) Close

func (b *EventBuffer) Close(ctx context.Context) error

Close stops the buffer and flushes remaining events. Requirement 33.7: flush on Shutdown()

func (*EventBuffer) DroppedCount

func (b *EventBuffer) DroppedCount() int64

DroppedCount returns the total number of events dropped due to buffer overflow. Requirement 33.9: increment events_dropped_total

func (*EventBuffer) Flush

func (b *EventBuffer) Flush(ctx context.Context) error

Flush immediately flushes all buffered events. Requirement 33.6

func (*EventBuffer) Size

func (b *EventBuffer) Size() int

Size returns the current number of buffered events. Requirement 33.10: expose buffer_size gauge

type EventBufferConfig

type EventBufferConfig struct {
	// BatchSize is the number of events that trigger an automatic flush.
	// Default: 100. Requirement 33.2
	BatchSize int

	// FlushInterval is the maximum time between flushes.
	// Default: 5 seconds. Requirement 33.3
	FlushInterval time.Duration

	// MaxBufferSize is the maximum number of events to buffer.
	// When exceeded, oldest events are dropped. Requirement 33.8
	MaxBufferSize int

	// FlushFunc is called to flush buffered events.
	FlushFunc func(ctx context.Context, events []*Event, encoded [][]byte) error
}

EventBufferConfig configures the event buffer.

type EventCheckpoint

type EventCheckpoint struct {
	// Name is a dot-separated event name, e.g. "payment.started".
	Name string
	// AtMS is milliseconds elapsed from Event.StartedAt to when this was recorded.
	AtMS int64
	// Attrs holds optional key-value context for this checkpoint.
	Attrs []Attr
}

EventCheckpoint is a named breadcrumb recorded inside a canonical event. Checkpoints are lightweight — they store a name, elapsed milliseconds, and optional attrs. They appear in the final emitted JSON under "checkpoints".

type EventClosedError

type EventClosedError struct {
	EventID string
	State   EventState
}

EventClosedError is returned when code attempts to mutate or finish an event after the lifecycle has moved past the mutable states.

func (*EventClosedError) Error

func (e *EventClosedError) Error() string

type EventFunc

type EventFunc func(ctx context.Context) error

EventFunc runs application work while the canonical event is active. Return a non-nil error to mark the event as failed.

type EventState

type EventState string
const (
	EventStateCreated          EventState = "created"
	EventStateActive           EventState = "active"
	EventStateFinished         EventState = "finished"
	EventStateEmitting         EventState = "emitting"
	EventStateEmitted          EventState = "emitted"
	EventStateFailedValidation EventState = "failed_validation"
	EventStateDeliveryFailed   EventState = "delivery_failed"
)

type EventView

type EventView interface {
	SchemaVersion() string
	EventVersion() string
	ID() string
	Name() string
	Kind() string
	Message() string
	RequestID() string
	TraceID() string
	SpanID() string
	ParentID() string
	Timestamp() time.Time
	StartedAt() time.Time
	FinishedAt() time.Time
	DurationMS() int64
	Service() string
	Version() string
	Environment() string
	DeploymentID() string
	Region() string
	Host() string
	Runtime() string
	Method() string
	Path() string
	Route() string
	StatusCode() int
	Level() Level
	Outcome() string
	Error() *ErrorInfo

	Attr(key string) any
	Attrs() map[string]any
	Group(name string) map[string]any
	Checkpoints() []EventCheckpoint
}

EventView is a read-only view over an event used by schemas.

type FieldNamingConfig

type FieldNamingConfig struct {
	// ExpandDotKeys splits keys like "user.id" into nested JSON objects.
	// Default: true.
	ExpandDotKeys bool
}

FieldNamingConfig controls how custom attr keys are treated during encoding.

type FileConfig

type FileConfig struct {
	CollectorURL      string `yaml:"collector_url"`
	ServiceName       string `yaml:"service_name"`
	ServiceVersion    string `yaml:"service_version"`
	Environment       string `yaml:"environment"`
	TenantID          string `yaml:"tenant_id"`
	BatchSize         int    `yaml:"batch_size"`
	FlushInterval     string `yaml:"flush_interval"`
	MaxBufferSize     int    `yaml:"max_buffer_size"`
	MaxRetries        int    `yaml:"max_retries"`
	MaxBackoff        string `yaml:"max_backoff"`
	Timeout           string `yaml:"timeout"`
	ConnectionTimeout string `yaml:"connection_timeout"`
	EnableCompression *bool  `yaml:"enable_compression"`
}

FileConfig is the YAML-serializable representation of SDK configuration. It maps to the loxa.yaml file format.

func LoadDefaultsFile

func LoadDefaultsFile() (FileConfig, error)

LoadDefaultsFile loads repo-level SDK defaults from loxa-go.defaults.yaml.

func LoadFromFile

func LoadFromFile(path string) (FileConfig, error)

LoadFromFile loads configuration from a loxa.yaml file. If path is empty, it searches for loxa.yaml in the current directory, then in the user's home directory (~/.loxa/loxa.yaml).

Returns ErrConfigFileNotFound if no config file is found. Returns a parse error if the file exists but cannot be parsed.

This implements Requirement 32.3.

type HTTPResponse

type HTTPResponse struct {
	StatusCode int
	Body       []byte
	Headers    http.Header
}

HTTPResponse represents the response from an HTTP request.

type HTTPTransport

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

HTTPTransport provides HTTP client with retry logic for event delivery.

func NewHTTPTransport

func NewHTTPTransport(cfg HTTPTransportConfig) *HTTPTransport

NewHTTPTransport creates a new HTTP transport with retry logic.

func (*HTTPTransport) Client

func (t *HTTPTransport) Client() *http.Client

Client returns the underlying HTTP client.

func (*HTTPTransport) Do

Do executes an HTTP request with retry logic. It implements exponential backoff with jitter and honors Retry-After headers.

type HTTPTransportConfig

type HTTPTransportConfig struct {
	MaxRetries        int
	MaxBackoff        time.Duration
	Timeout           time.Duration
	ConnectionTimeout time.Duration
	Client            *http.Client
	Metrics           *MetricsCollector
}

HTTPTransportConfig configures the HTTP transport.

type IDGenerator

type IDGenerator interface {
	NewID() string
}

IDGenerator generates unique string IDs for events.

type JSONEventEncoder

type JSONEventEncoder struct {
	Pretty        bool
	ExpandDotKeys bool
	TimeFormat    TimeFormat
}

JSONEventEncoder is the default Encoder producing compact or pretty NDJSON.

func JSONEncoder

func JSONEncoder() *JSONEventEncoder

JSONEncoder returns the default compact JSON encoder.

func PrettyJSONEncoder

func PrettyJSONEncoder() *JSONEventEncoder

PrettyJSONEncoder returns a pretty-print JSON encoder.

func (*JSONEventEncoder) EncodeEvent

func (e *JSONEventEncoder) EncodeEvent(dst []byte, ev *Event) ([]byte, error)

EncodeEvent encodes ev into dst and returns the extended slice.

type Kind

type Kind uint8

Kind identifies the type stored in an Attr's Value field. Using Kind avoids reflection on the hot encoding path.

const (
	KindString   Kind = iota
	KindInt           // stored as int
	KindInt64         // stored as int64
	KindUint64        // stored as uint64
	KindFloat64       // stored as float64
	KindBool          // stored as bool
	KindTime          // stored as time.Time
	KindDuration      // stored as time.Duration
	KindGroup         // stored as []Attr
	KindAny           // stored as any — slow path via encoding/json
	KindStringer      // stored as fmt.Stringer
	KindError         // stored as error
	KindNull          // stored as nil
)

type LeafValue

type LeafValue struct {
	Kind  uint8 // matches loxa.Kind
	Value any
}

LeafValue carries the typed value of a leaf node.

type Level

type Level uint8

Level represents the severity level of a log event.

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

func Parse

func Parse(s string) Level

Parse parses a string into a Level. Defaults to LevelInfo on unknown input.

func ParseLevel

func ParseLevel(s string) Level

ParseLevel parses a string into a Level. Defaults to LevelInfo on unknown input.

func (Level) String

func (l Level) String() string

String returns the lower-case string representation of the level.

type Logger

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

Logger is an instance of the LOXA-Go logging pipeline.

func Default

func Default() *Logger

Default returns the global default Logger.

func New

func New(cfg Config) (*Logger, error)

New creates a Logger from cfg, validating and applying defaults.

func NewClient

func NewClient(cfg Config) (*Logger, error)

NewClient creates a new Logger applying the full configuration precedence: code initialization > environment variables > configuration file > defaults.

This implements Requirement 32.1, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9.

The cfg parameter represents code-level configuration (highest precedence). Environment variables are loaded automatically. A loxa.yaml file is loaded from the current directory if present.

func (*Logger) Add

func (l *Logger) Add(ctx context.Context, key string, value interface{}) error

Add appends a value to an array field on the active event. Requirements: 2.4

func (*Logger) Append

func (l *Logger) Append(ctx context.Context, attrs ...Attr) error

Append appends attrs to the canonical event in ctx.

func (*Logger) Checkpoint

func (l *Logger) Checkpoint(ctx context.Context, name string, attrs ...Attr) error

Checkpoint records a named breadcrumb inside the event.

func (*Logger) Child

func (l *Logger) Child(options ...ConfigOption) (*Logger, error)

Child creates a nested logger with config overrides applied.

func (*Logger) Close

func (l *Logger) Close() error

Close is an alias for Shutdown. It implements Requirement 2.9 and 32.10.

func (*Logger) Config

func (l *Logger) Config() Config

Config returns a copy of the logger's current configuration.

func (*Logger) Debug

func (l *Logger) Debug(msg string, attrs ...Attr)

Debug emits an immediate debug log line.

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, msg, event string, attrs ...Attr)

DebugContext emits an immediate debug log line with explicit context and event name.

func (*Logger) Delete

func (l *Logger) Delete(ctx context.Context, keys ...string) error

Delete removes attrs by key from the active event.

func (*Logger) Emit

func (l *Logger) Emit(ctx context.Context) error

Emit encodes and delivers the canonical event in ctx to all sinks. Idempotent — safe to call via defer and also explicitly.

func (*Logger) EmitEvent

func (l *Logger) EmitEvent(ev *Event) error

EmitEvent encodes and delivers ev directly.

func (*Logger) EmitEventWithContext

func (l *Logger) EmitEventWithContext(ctx context.Context, ev *Event) error

EmitEventWithContext encodes and delivers ev with the given context.

func (*Logger) Enrich

func (l *Logger) Enrich(ctx context.Context, attrs ...Attr) error

Enrich appends attrs to the canonical event in ctx.

func (*Logger) EnrichGroup

func (l *Logger) EnrichGroup(ctx context.Context, key string, attrs ...Attr) error

EnrichGroup appends attrs as a named group to the event in ctx.

func (*Logger) Error

func (l *Logger) Error(msg string, attrs ...Attr)

Error emits an immediate error log line.

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, msg string, err error, event string, attrs ...Attr)

ErrorContext emits an immediate error log line with explicit context and event name.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, attrs ...Attr)

Fatal emits an immediate fatal log line and exits the process.

func (*Logger) Finish

func (l *Logger) Finish(ctx context.Context, outcome string, attrs ...Attr) error

Finish records the outcome and computes duration.

func (*Logger) FinishError

func (l *Logger) FinishError(ctx context.Context, err error, attrs ...Attr) error

FinishError records an error outcome, extracts error metadata, and computes duration.

func (*Logger) Flush

func (l *Logger) Flush(ctx context.Context) error

Flush drains the async queue and flushes all sinks.

func (*Logger) Get

func (l *Logger) Get(ctx context.Context, key string) (any, bool)

Get reads a value by key (dot-path supported) from the active event.

func (*Logger) GetGroup

func (l *Logger) GetGroup(ctx context.Context, key string) (map[string]any, bool)

GetGroup reads a group object by key from the active event.

func (*Logger) Info

func (l *Logger) Info(msg string, attrs ...Attr)

Info emits an immediate info log line.

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, msg, event string, attrs ...Attr)

InfoContext emits an immediate info log line with explicit context and event name.

func (*Logger) Merge

func (l *Logger) Merge(ctx context.Context, group string, attrs ...Attr) error

Merge merges attrs into a named group on the active event.

func (*Logger) PanicRecoveryEnabled

func (l *Logger) PanicRecoveryEnabled() bool

PanicRecoveryEnabled reports whether runtime wrappers should recover panics.

func (*Logger) Set

func (l *Logger) Set(ctx context.Context, attrs ...Attr) error

Set upserts attrs on the active event.

func (*Logger) Shutdown

func (l *Logger) Shutdown(ctx context.Context) error

Shutdown drains, flushes, and closes all sinks.

func (*Logger) StartEvent

func (l *Logger) StartEvent(ctx context.Context, params Params) context.Context

StartEvent begins a canonical wide event, stores it in ctx, and returns the new ctx. Requirements: 39.1, 39.2, 39.3, 39.4, 39.5, 39.6, 39.7, 39.8

func (*Logger) Warn

func (l *Logger) Warn(msg string, attrs ...Attr)

Warn emits an immediate warn log line.

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, msg, event string, attrs ...Attr)

WarnContext emits an immediate warn log line with explicit context and event name.

func (*Logger) WithSchema

func (l *Logger) WithSchema(schema Schema) (*Logger, error)

WithSchema creates a nested logger with a different output schema.

type MemorySinkStore

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

func (*MemorySinkStore) Clear

func (m *MemorySinkStore) Clear()

func (*MemorySinkStore) Events

func (m *MemorySinkStore) Events() []*Event

func (*MemorySinkStore) Len

func (m *MemorySinkStore) Len() int

func (*MemorySinkStore) Raw

func (m *MemorySinkStore) Raw() [][]byte

type MetricsCollector

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

MetricsCollector implements Prometheus metrics for the SDK. Requirements: 49.1, 49.2, 49.3, 49.4, 49.5, 49.6, 49.7, 49.8, 49.9, 49.10

func NewMetricsCollector

func NewMetricsCollector(namespace string, maxBufferSize int) *MetricsCollector

NewMetricsCollector creates a new Prometheus metrics collector for the SDK. Requirements: 49.10

func (*MetricsCollector) Handler

func (mc *MetricsCollector) Handler() http.Handler

Handler returns an HTTP handler for Prometheus metrics endpoint. Requirement: 49.10

func (*MetricsCollector) ObserveEmitDuration

func (mc *MetricsCollector) ObserveEmitDuration(duration time.Duration)

ObserveEmitDuration records the duration of an Emit operation. Requirement: 49.5

func (*MetricsCollector) OnBackpressure

func (mc *MetricsCollector) OnBackpressure()

OnBackpressure increments the backpressure_total counter. Requirement: 49.9

func (*MetricsCollector) OnEventCreated

func (mc *MetricsCollector) OnEventCreated()

OnEventCreated increments the events_created_total counter. Requirement: 49.1

func (*MetricsCollector) OnEventDropped

func (mc *MetricsCollector) OnEventDropped(reason string)

OnEventDropped increments the events_dropped_total counter with reason label. Requirement: 49.4

func (*MetricsCollector) OnEventEmitted

func (mc *MetricsCollector) OnEventEmitted(success bool)

OnEventEmitted increments the events_emitted_total counter with status label. Requirement: 49.3

func (*MetricsCollector) OnEventFinished

func (mc *MetricsCollector) OnEventFinished()

OnEventFinished increments the events_finished_total counter. Requirement: 49.2

func (*MetricsCollector) OnRetry

func (mc *MetricsCollector) OnRetry(attempt int)

OnRetry increments the retry_total counter with attempt label. Requirement: 49.8

func (*MetricsCollector) Registry

func (mc *MetricsCollector) Registry() *prometheus.Registry

Registry returns the Prometheus registry for custom registration. Requirement: 49.11

func (*MetricsCollector) SetBufferSize

func (mc *MetricsCollector) SetBufferSize(size int)

SetBufferSize sets the current buffer size directly. Requirement: 49.6

type Params

type Params struct {
	// ── Identity ────────────────────────────────────────────────────────────
	Event   string
	Name    string
	Kind    string
	Message string
	Level   Level

	// ── Correlation IDs ──────────────────────────────────────────────────────
	RequestID string
	TraceID   string
	SpanID    string
	ParentID  string

	// ── Service metadata ─────────────────────────────────────────────────────
	Service      string
	Version      string
	Environment  string
	DeploymentID string
	Region       string
	Host         string
	Runtime      string

	// ── Request metadata ─────────────────────────────────────────────────────
	Method     string
	Path       string
	Route      string
	StatusCode int
	DurationMS int64
	Outcome    string

	// ── Canonical subject identifiers ───────────────────────────────────────
	UserID         string
	TenantID       string
	WorkspaceID    string
	OrganizationID string
	SessionID      string

	// ── Timing ───────────────────────────────────────────────────────────────
	StartedAt time.Time

	// ── Custom business context ───────────────────────────────────────────────
	// Custom holds domain-specific attrs that LOXA-Go does not know in advance.
	// These are copied into Event.Attrs during StartEvent.
	Custom []Attr
}

Params holds all inputs for starting a canonical event. Canonical fields are first-class struct members; extra business context goes in Custom or is added later via Enrich.

func (Params) With

func (p Params) With(attrs ...Attr) Params

With returns a copy of p with additional attrs appended to Custom. It enables a builder style:

loxa.Params{Event: "checkout.request"}.With(
    loxa.String("tenant.id", tenantID),
)

type Pipeline

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

Pipeline manages the async event emission queue.

func NewPipeline

func NewPipeline(cfg PipelineConfig) *Pipeline

NewPipeline creates and starts the async pipeline.

func (*Pipeline) Enqueue

func (p *Pipeline) Enqueue(item PipelineItem) (bool, error)

Enqueue sends an item to the async queue per the backpressure policy.

func (*Pipeline) Flush

func (p *Pipeline) Flush(ctx context.Context) error

Flush drains the queue and flushes sinks.

func (*Pipeline) Shutdown

func (p *Pipeline) Shutdown(ctx context.Context) error

Shutdown closes the pipeline and waits for drain.

type PipelineConfig

type PipelineConfig struct {
	QueueSize     int
	Workers       int
	FlushInterval time.Duration
	MaxBatchBytes int
	Backpressure  BackpressurePolicy
	Sinks         []SinkWriter
	Fallback      SinkWriter
	OnDrop        func(reason string)
	OnError       func(err error)
}

PipelineConfig carries the settings the pipeline needs.

type PipelineItem

type PipelineItem struct {
	Encoded []byte
	Event   *Event
	Level   int // 0=debug, 1=info, 2=warn, 3=error — used by drop policies
	IsError bool
}

PipelineItem carries encoded event bytes to workers.

type PrometheusStatsHandler

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

PrometheusStatsHandler wraps MetricsCollector to implement StatsHandler interface. Requirements: 34.3, 34.4

func NewPrometheusStatsHandler

func NewPrometheusStatsHandler(namespace string, maxBufferSize int) *PrometheusStatsHandler

NewPrometheusStatsHandler creates a new StatsHandler backed by Prometheus metrics.

func (*PrometheusStatsHandler) Handler

func (h *PrometheusStatsHandler) Handler() http.Handler

Handler returns an HTTP handler for the Prometheus metrics endpoint.

func (*PrometheusStatsHandler) Metrics

Metrics returns the underlying MetricsCollector for direct access.

func (*PrometheusStatsHandler) ObserveEmitDuration

func (h *PrometheusStatsHandler) ObserveEmitDuration(d time.Duration)

ObserveEmitDuration records the duration of an emit operation.

func (*PrometheusStatsHandler) OnDeliveryFailed

func (h *PrometheusStatsHandler) OnDeliveryFailed(_ *Event, _ error)

OnDeliveryFailed records an explicit delivery failure without counting it as a success emit.

func (*PrometheusStatsHandler) OnDrop

func (h *PrometheusStatsHandler) OnDrop(reason string)

OnDrop is called when an event is dropped. Requirement: 34.4

func (*PrometheusStatsHandler) OnEmit

func (h *PrometheusStatsHandler) OnEmit(ev *Event)

OnEmit is called when an event is successfully emitted. Requirement: 34.3

func (*PrometheusStatsHandler) OnError

func (h *PrometheusStatsHandler) OnError(err error)

OnError is called when an error occurs during asynchronous operations. Requirement: 34.3, 34.4

func (*PrometheusStatsHandler) OnEventCreated

func (h *PrometheusStatsHandler) OnEventCreated()

OnEventCreated increments the events_created_total counter.

func (*PrometheusStatsHandler) OnEventFinished

func (h *PrometheusStatsHandler) OnEventFinished()

OnEventFinished increments the events_finished_total counter.

type Redactor

type Redactor interface {
	// Redact examines key and value. It returns the (possibly modified) value
	// and whether to keep the field. Return keep=false to drop the field entirely.
	Redact(key string, value any) (newValue any, keep bool)
}

Redactor scrubs sensitive values from an event before encoding.

func ComposeRedactors

func ComposeRedactors(redactors ...Redactor) Redactor

ComposeRedactors combines multiple redactors; the first match wins.

func DefaultRedactor

func DefaultRedactor() Redactor

DefaultRedactor returns a Redactor that replaces common sensitive keys.

func DropKeys

func DropKeys(keys ...string) Redactor

DropKeys returns a Redactor that removes fields with the given keys.

func HashKeys

func HashKeys(keys ...string) Redactor

HashKeys returns a Redactor that hashes values for the given keys.

func MaskKeys

func MaskKeys(keys ...string) Redactor

MaskKeys returns a Redactor that partially masks values for given keys.

func RedactKeys

func RedactKeys(keys ...string) Redactor

RedactKeys returns a Redactor that replaces values for the given keys.

type RetriableError

type RetriableError interface {
	Retriable() bool
}

RetriableError is implemented by errors that signal whether retry is safe.

type RotatingFileConfig

type RotatingFileConfig struct {
	Path     string
	MaxBytes int64
	MaxAge   time.Duration
}

RotatingFileConfig configures the rotating file sink.

type Sampler

type Sampler interface {
	ShouldSample(ev *Event) bool
}

Sampler decides whether an event should be emitted.

func AllSampler

func AllSampler(samplers ...Sampler) Sampler

AllSampler keeps an event only if all samplers keep it.

func AnySampler

func AnySampler(samplers ...Sampler) Sampler

AnySampler keeps an event if any sampler keeps it.

func NotSampler

func NotSampler(s Sampler) Sampler

NotSampler inverts another sampler.

func SampleAll

func SampleAll() Sampler

SampleAll keeps every event.

func SampleByHeader

func SampleByHeader(header, value string) Sampler

SampleByHeader keeps events where a header attr equals value. It checks keys:

  • http.header.<name>
  • http.headers.<name>
  • <name>

where <name> is lower-cased with "_" converted to "-".

func SampleErrors

func SampleErrors() Sampler

SampleErrors keeps only error events.

func SampleFeatureFlag

func SampleFeatureFlag(name string, value any) Sampler

SampleFeatureFlag keeps events where feature/feature_flags.<name> matches value.

func SampleNone

func SampleNone() Sampler

SampleNone drops every event.

func SampleRandom

func SampleRandom(rate float64) Sampler

SampleRandom keeps approximately rate of events (0..1).

func SampleRateLimited

func SampleRateLimited(rate float64, window time.Duration) Sampler

SampleRateLimited keeps at most rate events per window using a token-bucket strategy.

func SampleRoutes

func SampleRoutes(routes ...string) Sampler

SampleRoutes keeps events whose route or path matches one of routes.

func SampleSlowRequests

func SampleSlowRequests(threshold any) Sampler

SampleSlowRequests keeps events with duration >= threshold. threshold may be time.Duration, int64 (milliseconds), or int (milliseconds).

func SampleStatusCodes

func SampleStatusCodes(codes ...int) Sampler

SampleStatusCodes keeps events whose status code matches one of codes.

func SampleTenants

func SampleTenants(ids ...string) Sampler

SampleTenants keeps events whose tenant identifier matches one of ids. It checks both "tenant.id" and "tenant_id".

func SampleUsers

func SampleUsers(ids ...string) Sampler

SampleUsers keeps events whose user identifier matches one of ids. It checks both "user.id" and "user_id".

type Schema

type Schema interface {
	Encode(event EventView) ([]byte, error)
}

Schema controls final output shape for emitted events.

func CustomSchema

func CustomSchema(fn func(EventView) map[string]any) Schema

CustomSchema creates a schema from a projection function.

func DatadogSchema

func DatadogSchema() Schema

DatadogSchema emits a Datadog-like JSON shape.

func DefaultSchema

func DefaultSchema() Schema

DefaultSchema emits canonical LOXA output shape.

func ECSchema

func ECSchema() Schema

ECSchema emits an Elastic Common Schema-inspired log shape.

func FlatSchema

func FlatSchema() Schema

FlatSchema emits flattened attrs for analytics databases.

func NestedSchema

func NestedSchema() Schema

NestedSchema emits canonical fields with nested attrs/groups.

func OTelLogSchema

func OTelLogSchema() Schema

OTelLogSchema emits an OpenTelemetry-flavored log shape.

type SchemaFunc

type SchemaFunc func(event EventView) map[string]any

SchemaFunc allows mapping an EventView to an output object.

func (SchemaFunc) Encode

func (f SchemaFunc) Encode(event EventView) ([]byte, error)

Encode converts map output to NDJSON.

type SecurityConfig

type SecurityConfig struct {
	RedactByDefault     bool
	AllowPII            bool
	MaxFieldBytes       int
	MaxEventBytes       int
	MaxAttrCount        int
	DropOversizedEvents bool
}

SecurityConfig controls event-size and sensitive-data limits.

type Sink

type Sink interface {
	// Name returns a human-readable identifier for this sink.
	Name() string
	// WriteEvent delivers an already-encoded event to the sink.
	// encoded is the JSON bytes (including trailing newline).
	// ev is the original Event for sinks that need typed field access.
	WriteEvent(ctx context.Context, encoded []byte, ev *Event) error
	// Flush forces any buffered data to be written.
	Flush(ctx context.Context) error
	// Close releases resources held by the sink.
	Close(ctx context.Context) error
}

Sink receives encoded events and delivers them to a destination. All methods must be safe for concurrent use.

func CollectorSink

func CollectorSink(cfg CollectorSinkConfig) (Sink, error)

func FileSink

func FileSink(path string) (Sink, error)

FileSink returns a Sink that appends NDJSON to the file at path.

func HTTPBatchSink

func HTTPBatchSink(endpoint string) (Sink, error)

func NoopSink

func NoopSink() Sink

func RotatingFileSink

func RotatingFileSink(cfg RotatingFileConfig) (Sink, error)

RotatingFileSink returns a Sink that rotates log files.

func StderrSink

func StderrSink() Sink

StderrSink returns a Sink that writes NDJSON to os.Stderr.

func StdoutSink

func StdoutSink() Sink

StdoutSink returns a Sink that writes NDJSON to os.Stdout.

type SinkWriter

type SinkWriter interface {
	WriteEvent(ctx context.Context, encoded []byte, ev *Event) error
	Flush(ctx context.Context) error
	Close(ctx context.Context) error
}

SinkWriter is the minimal sink interface used by the pipeline. This avoids importing the root loxa package from internal/core.

type StackError

type StackError interface {
	StackTrace() string
}

StackError is implemented by errors that carry a stack trace string.

type StatsHandler

type StatsHandler interface {
	OnEmit(ev *Event)
	OnDrop(reason string)
	OnError(err error)
}

StatsHandler receives logger pipeline telemetry callbacks.

type TimeFormat

type TimeFormat int

TimeFormat controls how timestamps are serialised.

const (
	TimeFormatRFC3339     TimeFormat = iota // "2006-01-02T15:04:05Z07:00"
	TimeFormatRFC3339Nano                   // nanosecond precision
	TimeFormatUnixMS                        // milliseconds since epoch as integer
)

Jump to

Keyboard shortcuts

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