Documentation
¶
Overview ¶
Package core provides internal implementation utilities for LOXA-Go. These types are not part of the public API.
Index ¶
- Constants
- Variables
- func AssertEvent(t testing.TB, ev *Event, key string, expected any)
- func Configure(cfg Config) error
- func EventID(ctx context.Context) string
- func GenerateSpanID() string
- func GenerateTraceID() string
- func HasEvent(ctx context.Context) bool
- func InjectHTTPHeaderCarrier(ctx context.Context, header http.Header) http.Header
- func InjectHTTPHeaders(req *http.Request)
- func IsCanonical(key string) bool
- func IsValidSpanID(spanID string) bool
- func IsValidTraceID(traceID string) bool
- func MemorySink() (Sink, *MemorySinkStore)
- func NewEventMap(in BuildInput) map[string]any
- func NewRoundTripper(base http.RoundTripper) http.RoundTripper
- func NewUUIDv7() string
- func PanicRecoveryEnabled() bool
- func RequestIDFromContext(ctx context.Context) string
- func RequestIDFromHTTP(r *http.Request) string
- func RunCLI(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunCron(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunEvent(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunHTTP(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunJob(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunQueue(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func SetDefault(l *Logger)
- func SpanIDFromContext(ctx context.Context) string
- func TestLogger() (*Logger, *MemorySinkStore, error)
- func TraceFromOTel(ctx context.Context) (traceID string, spanID string)
- func TraceIDFromContext(ctx context.Context) string
- func ValidateIngestEnvelopeBytes(raw []byte, strict bool) error
- func WrapHTTPClient(client *http.Client) *http.Client
- type AsyncConfig
- type Attr
- func Amount(value int64) Attr
- func Any(key string, val any) Attr
- func AppVersion(value string) Attr
- func Attempt(n int) Attr
- func Bool(key string, val bool) Attr
- func CartID(id string) Attr
- func CartTotalCents(total int64) Attr
- func Country(code string) Attr
- func Currency(code string) Attr
- func CustomerID(id string) Attr
- func DeploymentID(id string) Attr
- func Device(value string) Attr
- func Duration(key string, val time.Duration) Attr
- func DurationMS(ms int64) Attr
- func Err(err error) Attr
- func ErrorCode(code string) Attr
- func ErrorMessage(msg string) Attr
- func ErrorStack(stack string) Attr
- func ErrorType(name string) Attr
- func Experiment(name, variant string) Attr
- func ExtractHTTPHeaderAttrs(header http.Header) []Attr
- func ExtractHTTPHeaderAttrsWithContext(ctx context.Context, header http.Header) []Attr
- func ExtractHTTPHeaders(r *http.Request) []Attr
- func FeatureFlag(name string, value any) Attr
- func FeatureFlagBool(name string, enabled bool) Attr
- func Float64(key string, val float64) Attr
- func Group(key string, attrs ...Attr) Attr
- func HashString(key, value string) Attr
- func Int(key string, val int) Attr
- func Int64(key string, val int64) Attr
- func JobName(name string) Attr
- func MarkSensitive(attr Attr) Attr
- func MessageID(id string) Attr
- func Method(method string) Attr
- func Null(key string) Attr
- func OrderID(id string) Attr
- func OrganizationID(id string) Attr
- func Outcome(outcome string) Attr
- func Path(path string) Attr
- func PaymentLatencyMS(ms int64) Attr
- func PaymentProvider(provider string) Attr
- func Plan(name string) Attr
- func Platform(value string) Attr
- func ProductID(id string) Attr
- func QueueName(name string) Attr
- func Region(region string) Attr
- func RequestID(id string) Attr
- func Retryable(v bool) Attr
- func Route(route string) Attr
- func SensitiveString(key, value string) Attr
- func Service(service string) Attr
- func SessionID(id string) Attr
- func SpanID(id string) Attr
- func StatusCode(code int) Attr
- func String(key, val string) Attr
- func Stringer(key string, val fmt.Stringer) Attr
- func TenantID(id string) Attr
- func Time(key string, val time.Time) Attr
- func TraceID(id string) Attr
- func Uint64(key string, val uint64) Attr
- func UserID(id string) Attr
- func UserSubscription(sub string) Attr
- func Version(version string) Attr
- func WorkspaceID(id string) Attr
- type BackpressurePolicy
- type BatchSinkWriter
- type BuildInput
- type CheckpointConfig
- type Clock
- type CodedError
- type CollectorSinkConfig
- type Config
- func (c Config) Validate() error
- func (c Config) WithAllowPII(allow bool) Config
- func (c Config) WithAsync(enabled bool) Config
- func (c Config) WithAsyncFlushInterval(interval time.Duration) Config
- func (c Config) WithAsyncMaxBatchBytes(maxBytes int) Config
- func (c Config) WithAsyncQueue(size int) Config
- func (c Config) WithBackpressure(policy BackpressurePolicy) Config
- func (c Config) WithCollectorEndpoint(endpoint string) Config
- func (c Config) WithCompression(enabled bool) Config
- func (c Config) WithDropOversizedEvents(drop bool) Config
- func (c Config) WithDuplicatePolicy(policy DuplicateFieldPolicy) Config
- func (c Config) WithEncoder(e Encoder) Config
- func (c Config) WithEnricher(fn ContextEnricher) Config
- func (c Config) WithEnvironment(environment string) Config
- func (c Config) WithEventSchema(schema Schema) Config
- func (c Config) WithFallbackSink(sink Sink) Config
- func (c Config) WithMaxAttrCount(max int) Config
- func (c Config) WithMaxEventBytes(max int) Config
- func (c Config) WithMaxFieldBytes(max int) Config
- func (c Config) WithRedactByDefault(redact bool) Config
- func (c Config) WithRedactor(r Redactor) Config
- func (c Config) WithSampler(s Sampler) Config
- func (c Config) WithSchema(schema Schema) Config
- func (c Config) WithService(service string) Config
- func (c Config) WithSink(sink Sink) Config
- func (c Config) WithStatsHandler(handler StatsHandler) Config
- func (c Config) WithStrict(strict bool) Config
- func (c Config) WithVersion(version string) Config
- func (c Config) WithWorkers(workers int) Config
- type ConfigOption
- func WithAsync(enabled bool) ConfigOption
- func WithAsyncFlushInterval(interval time.Duration) ConfigOption
- func WithAsyncMaxBatchBytes(maxBytes int) ConfigOption
- func WithAsyncQueue(size int) ConfigOption
- func WithBackpressure(policy BackpressurePolicy) ConfigOption
- func WithBatchSize(size int) ConfigOption
- func WithCollectorEndpoint(endpoint string) ConfigOption
- func WithCollectorURL(url string) ConfigOption
- func WithCompression(enabled bool) ConfigOption
- func WithConnectionTimeout(timeout time.Duration) ConfigOption
- func WithDuplicatePolicy(policy DuplicateFieldPolicy) ConfigOption
- func WithEncoder(encoder Encoder) ConfigOption
- func WithEnricher(enricher ContextEnricher) ConfigOption
- func WithEnvironment(environment string) ConfigOption
- func WithEventSchema(schema Schema) ConfigOption
- func WithFallbackSink(sink Sink) ConfigOption
- func WithFlushInterval(interval time.Duration) ConfigOption
- func WithMaxBackoff(backoff time.Duration) ConfigOption
- func WithMaxBufferSize(size int) ConfigOption
- func WithMaxRetries(retries int) ConfigOption
- func WithRedactor(redactor Redactor) ConfigOption
- func WithSampler(sampler Sampler) ConfigOption
- func WithSchema(schema Schema) ConfigOption
- func WithService(service string) ConfigOption
- func WithSink(sink Sink) ConfigOption
- func WithStatsHandler(handler StatsHandler) ConfigOption
- func WithStrict(strict bool) ConfigOption
- func WithTenantID(tenantID string) ConfigOption
- func WithTimeout(timeout time.Duration) ConfigOption
- func WithVersion(version string) ConfigOption
- func WithWorkers(workers int) ConfigOption
- type ConfigValidationError
- type ContextEnricher
- type DeliveryFailureHandler
- type DotNode
- type DuplicateEmitError
- type DuplicateFieldError
- type DuplicateFieldPolicy
- type Encoder
- type ErrorExtractor
- type ErrorInfo
- type Event
- func (e *Event) Add(key string, value interface{}) error
- func (e *Event) AddAttrs(attrs []Attr) error
- func (e *Event) AddCheckpoint(cp EventCheckpoint) error
- func (e *Event) Append(attrs ...Attr) error
- func (e *Event) AttrList() []Attr
- func (e *Event) Checkpoint(name string, attrs ...Attr) error
- func (e *Event) Clone() *Event
- func (e *Event) Delete(keys ...string) error
- func (e *Event) Duration() time.Duration
- func (e *Event) Emit() error
- func (e *Event) Enrich(attrs ...Attr) error
- func (e *Event) Finish(outcome string, attrs ...Attr) error
- func (e *Event) FinishError(err error, attrs ...Attr) error
- func (e *Event) Flush(ctx context.Context) error
- func (e *Event) Get(key string) (any, bool)
- func (e *Event) GetGroup(name string) (map[string]any, bool)
- func (e *Event) ID() string
- func (e *Event) IsEmitted() bool
- func (e *Event) IsFinished() bool
- func (e *Event) MarkEmitted() bool
- func (e *Event) Merge(group string, attrs ...Attr) error
- func (e *Event) MuLock()
- func (e *Event) MuUnlock()
- func (e *Event) Request() string
- func (e *Event) Set(attrs ...Attr) error
- func (e *Event) SetError(info *ErrorInfo)
- func (e *Event) SetLogger(l *Logger)
- func (e *Event) SetOutcome(outcome string)
- func (e *Event) StartTime() time.Time
- func (e *Event) State() EventState
- func (e *Event) String() string
- func (e *Event) Trace() string
- type EventAlreadyFinishedError
- type EventBuffer
- type EventBufferConfig
- type EventCheckpoint
- type EventClosedError
- type EventFunc
- type EventState
- type EventView
- type FieldNamingConfig
- type FileConfig
- type HTTPResponse
- type HTTPTransport
- type HTTPTransportConfig
- type IDGenerator
- type JSONEventEncoder
- type Kind
- type LeafValue
- type Level
- type Logger
- func (l *Logger) Add(ctx context.Context, key string, value interface{}) error
- func (l *Logger) Append(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Checkpoint(ctx context.Context, name string, attrs ...Attr) error
- func (l *Logger) Child(options ...ConfigOption) (*Logger, error)
- func (l *Logger) Close() error
- func (l *Logger) Config() Config
- func (l *Logger) Debug(msg string, attrs ...Attr)
- func (l *Logger) DebugContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) Delete(ctx context.Context, keys ...string) error
- func (l *Logger) Emit(ctx context.Context) error
- func (l *Logger) EmitEvent(ev *Event) error
- func (l *Logger) EmitEventWithContext(ctx context.Context, ev *Event) error
- func (l *Logger) Enrich(ctx context.Context, attrs ...Attr) error
- func (l *Logger) EnrichGroup(ctx context.Context, key string, attrs ...Attr) error
- func (l *Logger) Error(msg string, attrs ...Attr)
- func (l *Logger) ErrorContext(ctx context.Context, msg string, err error, event string, attrs ...Attr)
- func (l *Logger) Fatal(msg string, attrs ...Attr)
- func (l *Logger) Finish(ctx context.Context, outcome string, attrs ...Attr) error
- func (l *Logger) FinishError(ctx context.Context, err error, attrs ...Attr) error
- func (l *Logger) Flush(ctx context.Context) error
- func (l *Logger) Get(ctx context.Context, key string) (any, bool)
- func (l *Logger) GetGroup(ctx context.Context, key string) (map[string]any, bool)
- func (l *Logger) Info(msg string, attrs ...Attr)
- func (l *Logger) InfoContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) Merge(ctx context.Context, group string, attrs ...Attr) error
- func (l *Logger) PanicRecoveryEnabled() bool
- func (l *Logger) Set(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Shutdown(ctx context.Context) error
- func (l *Logger) StartEvent(ctx context.Context, params Params) context.Context
- func (l *Logger) Warn(msg string, attrs ...Attr)
- func (l *Logger) WarnContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) WithSchema(schema Schema) (*Logger, error)
- type MemorySinkStore
- type MetricsCollector
- func (mc *MetricsCollector) Handler() http.Handler
- func (mc *MetricsCollector) ObserveEmitDuration(duration time.Duration)
- func (mc *MetricsCollector) OnBackpressure()
- func (mc *MetricsCollector) OnEventCreated()
- func (mc *MetricsCollector) OnEventDropped(reason string)
- func (mc *MetricsCollector) OnEventEmitted(success bool)
- func (mc *MetricsCollector) OnEventFinished()
- func (mc *MetricsCollector) OnRetry(attempt int)
- func (mc *MetricsCollector) Registry() *prometheus.Registry
- func (mc *MetricsCollector) SetBufferSize(size int)
- type Params
- type Pipeline
- type PipelineConfig
- type PipelineItem
- type PrometheusStatsHandler
- func (h *PrometheusStatsHandler) Handler() http.Handler
- func (h *PrometheusStatsHandler) Metrics() *MetricsCollector
- func (h *PrometheusStatsHandler) ObserveEmitDuration(d time.Duration)
- func (h *PrometheusStatsHandler) OnDeliveryFailed(_ *Event, _ error)
- func (h *PrometheusStatsHandler) OnDrop(reason string)
- func (h *PrometheusStatsHandler) OnEmit(ev *Event)
- func (h *PrometheusStatsHandler) OnError(err error)
- func (h *PrometheusStatsHandler) OnEventCreated()
- func (h *PrometheusStatsHandler) OnEventFinished()
- type Redactor
- type RetriableError
- type RotatingFileConfig
- type Sampler
- func AllSampler(samplers ...Sampler) Sampler
- func AnySampler(samplers ...Sampler) Sampler
- func NotSampler(s Sampler) Sampler
- func SampleAll() Sampler
- func SampleByHeader(header, value string) Sampler
- func SampleErrors() Sampler
- func SampleFeatureFlag(name string, value any) Sampler
- func SampleNone() Sampler
- func SampleRandom(rate float64) Sampler
- func SampleRateLimited(rate float64, window time.Duration) Sampler
- func SampleRoutes(routes ...string) Sampler
- func SampleSlowRequests(threshold any) Sampler
- func SampleStatusCodes(codes ...int) Sampler
- func SampleTenants(ids ...string) Sampler
- func SampleUsers(ids ...string) Sampler
- type Schema
- type SchemaFunc
- type SecurityConfig
- type Sink
- type SinkWriter
- type StackError
- type StatsHandler
- type TimeFormat
Constants ¶
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 )
const ( LOXA_SPEC_VERSION = speccontract.LOXASpecVersion LOXA_INGEST_API_VERSION = speccontract.LOXAIngestAPIVersion LOXA_EVENT_VERSION = speccontract.LOXAEventVersion )
Variables ¶
var CanonicalFieldSet = speccontract.CanonicalFieldSet
CanonicalFieldSet is the generated set of top-level canonical JSON field names.
var ErrConfigFileNotFound = errors.New("loxa: config file not found")
ErrConfigFileNotFound is returned when no config file is found.
var ErrInvalidConfig = errors.New("loxa: invalid config")
ErrInvalidConfig is returned when configuration validation fails.
var ErrPipelineClosed = errors.New("pipeline closed")
ErrPipelineClosed is returned when enqueueing after shutdown starts.
Functions ¶
func AssertEvent ¶
AssertEvent asserts a key on event attrs equals expected.
func Configure ¶
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 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 InjectHTTPHeaderCarrier ¶
InjectHTTPHeaderCarrier injects LOXA and trace context into headers.
func InjectHTTPHeaders ¶
InjectHTTPHeaders injects LOXA + trace context headers into an outbound request.
func IsCanonical ¶
IsCanonical returns true if key matches a canonical field name.
func IsValidSpanID ¶
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 ¶
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 ¶
RequestIDFromContext returns the request id from ctx when present.
func RequestIDFromHTTP ¶
RequestIDFromHTTP resolves request id from header, then active event context.
func RunEvent ¶
RunEvent wraps an operation in the canonical lifecycle: StartEvent -> fn -> Finish/FinishError -> Emit.
func SetDefault ¶
func SetDefault(l *Logger)
SetDefault replaces the global default logger instance.
func SpanIDFromContext ¶
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 ¶
TraceFromOTel returns trace and span ids from the current OTel span context.
func TraceIDFromContext ¶
TraceIDFromContext returns the trace id from ctx when present.
func ValidateIngestEnvelopeBytes ¶
ValidateIngestEnvelopeBytes validates a runtime envelope payload against the generated contract before it is sent to the collector.
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 ¶
Attr is a typed key-value pair used to enrich canonical events. Canonical fields use Kind to skip reflection on the fast path.
func DeploymentID ¶
DeploymentID sets the canonical deployment_id field.
func Experiment ¶
Experiment adds an experiment variant field.
func ExtractHTTPHeaderAttrs ¶
ExtractHTTPHeaderAttrs converts common tracing/request headers into attrs.
func ExtractHTTPHeaderAttrsWithContext ¶
ExtractHTTPHeaderAttrsWithContext converts common tracing/request headers into attrs.
func ExtractHTTPHeaders ¶
ExtractHTTPHeaders converts common tracing/request headers into attrs.
func FeatureFlag ¶
FeatureFlag adds a feature flag entry under the feature group.
func FeatureFlagBool ¶
FeatureFlagBool adds a boolean feature flag.
func Group ¶
Group creates a nested object Attr.
loxa.Group("user", loxa.String("id", uid), loxa.String("plan", "pro"))
→ {"user":{"id":"...","plan":"pro"}}
func HashString ¶
HashString stores a hash-ready marker field for sensitive values.
func MarkSensitive ¶
MarkSensitive marks attr key as sensitive metadata.
func PaymentLatencyMS ¶
PaymentLatencyMS sets payment.latency_ms.
func PaymentProvider ¶
PaymentProvider sets payment.provider.
func SensitiveString ¶
SensitiveString marks a string field as sensitive.
func UserSubscription ¶
UserSubscription sets user.subscription.
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 ¶
Clock abstracts time to allow deterministic testing.
func NewMockClock ¶
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 ¶
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 ¶
Validate validates cfg and returns explicit field-level errors. In strict mode, additional config checks are enforced.
func (Config) WithAllowPII ¶
WithAllowPII enables or disables PII exposure when RedactByDefault is true.
func (Config) WithAsyncFlushInterval ¶
WithAsyncFlushInterval sets async flush interval and enables async mode.
func (Config) WithAsyncMaxBatchBytes ¶
WithAsyncMaxBatchBytes sets async max batch size and enables async mode.
func (Config) WithAsyncQueue ¶
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 (Config) WithCompression ¶
WithCompression enables or disables gzip compression for collector requests.
func (Config) WithDropOversizedEvents ¶
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 ¶
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 ¶
WithEnvironment returns a copy of cfg with Environment set.
func (Config) WithEventSchema ¶
WithEventSchema sets the output event schema.
func (Config) WithFallbackSink ¶
WithFallbackSink configures a sink used when primary sink writes fail.
func (Config) WithMaxAttrCount ¶
WithMaxAttrCount sets the maximum number of attributes per event.
func (Config) WithMaxEventBytes ¶
WithMaxEventBytes sets the maximum byte size for entire events.
func (Config) WithMaxFieldBytes ¶
WithMaxFieldBytes sets the maximum byte size for individual field values.
func (Config) WithRedactByDefault ¶
WithRedactByDefault enables or disables redaction of sensitive fields by default.
func (Config) WithRedactor ¶
WithRedactor sets the redactor.
func (Config) WithSampler ¶
WithSampler sets the sampler.
func (Config) WithSchema ¶
WithSchema sets the output event schema.
func (Config) WithService ¶
WithService returns a copy of cfg with Service set.
func (Config) WithStatsHandler ¶
func (c Config) WithStatsHandler(handler StatsHandler) Config
WithStatsHandler sets callbacks for emit/drop/error telemetry.
func (Config) WithStrict ¶
WithStrict enables or disables strict mode validation.
func (Config) WithVersion ¶
WithVersion returns a copy of cfg with Version set.
func (Config) WithWorkers ¶
WithWorkers sets async worker count and enables async mode.
type ConfigOption ¶
ConfigOption mutates and returns a Config.
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 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 WithStatsHandler ¶
func WithStatsHandler(handler StatsHandler) ConfigOption
WithStatsHandler applies stats handler callbacks.
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 WithWorkers ¶
func WithWorkers(workers int) ConfigOption
WithWorkers applies async worker count.
type ConfigValidationError ¶
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 ¶
ContextEnricher appends attrs derived from request/job context during Emit.
type DeliveryFailureHandler ¶
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 ErrorExtractor ¶
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 ¶
DefaultErrorExtractor is the built-in extractor used when none is configured.
func DefaultErrorExtractorNoStack ¶
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 FromContext ¶
FromContext retrieves the canonical Event from ctx. Returns (nil, false) if StartEvent has not been called.
func (*Event) Add ¶
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) AddCheckpoint ¶
func (e *Event) AddCheckpoint(cp EventCheckpoint) error
AddCheckpoint appends an EventCheckpoint under the mutex.
func (*Event) Checkpoint ¶
Checkpoint records a checkpoint on this event.
func (*Event) Delete ¶
Delete removes attrs by key. Dot keys can target group children (e.g. "user.id").
func (*Event) FinishError ¶
FinishError marks this event as failed.
func (*Event) IsFinished ¶
IsFinished reports if event finish timestamp is set.
func (*Event) MarkEmitted ¶
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) MuLock ¶
func (e *Event) MuLock()
MuLock acquires the event mutex. Use sparingly; prefer the accessor methods.
func (*Event) Set ¶
Set upserts attrs by key and applies canonical fields when keys match. Requirements: 1.3, 2.3
func (*Event) SetOutcome ¶
SetOutcome sets the Outcome field.
func (*Event) State ¶
func (e *Event) State() EventState
State returns the current event state for observability. Requirements: 1.10
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 ¶
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 ¶
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 ¶
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 ¶
func (t *HTTPTransport) Do(ctx context.Context, req *http.Request) (*HTTPResponse, error)
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 Level ¶
type Level uint8
Level represents the severity level of a log event.
func ParseLevel ¶
ParseLevel parses a string into a Level. Defaults to LevelInfo on unknown input.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is an instance of the LOXA-Go logging pipeline.
func NewClient ¶
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) Checkpoint ¶
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) DebugContext ¶
DebugContext emits an immediate debug log line with explicit context and event name.
func (*Logger) Emit ¶
Emit encodes and delivers the canonical event in ctx to all sinks. Idempotent — safe to call via defer and also explicitly.
func (*Logger) EmitEventWithContext ¶
EmitEventWithContext encodes and delivers ev with the given context.
func (*Logger) EnrichGroup ¶
EnrichGroup appends attrs as a named group to the event in ctx.
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) FinishError ¶
FinishError records an error outcome, extracts error metadata, and computes duration.
func (*Logger) InfoContext ¶
InfoContext emits an immediate info log line with explicit context and event name.
func (*Logger) PanicRecoveryEnabled ¶
PanicRecoveryEnabled reports whether runtime wrappers should recover panics.
func (*Logger) StartEvent ¶
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) WarnContext ¶
WarnContext emits an immediate warn log line with explicit context and event name.
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.
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.
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 ¶
func (h *PrometheusStatsHandler) Metrics() *MetricsCollector
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 ¶
ComposeRedactors combines multiple redactors; the first match wins.
func DefaultRedactor ¶
func DefaultRedactor() Redactor
DefaultRedactor returns a Redactor that replaces common sensitive keys.
func RedactKeys ¶
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 ¶
RotatingFileConfig configures the rotating file sink.
type Sampler ¶
Sampler decides whether an event should be emitted.
func AllSampler ¶
AllSampler keeps an event only if all samplers keep it.
func AnySampler ¶
AnySampler keeps an event if any sampler keeps it.
func SampleByHeader ¶
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 SampleFeatureFlag ¶
SampleFeatureFlag keeps events where feature/feature_flags.<name> matches value.
func SampleRandom ¶
SampleRandom keeps approximately rate of events (0..1).
func SampleRateLimited ¶
SampleRateLimited keeps at most rate events per window using a token-bucket strategy.
func SampleRoutes ¶
SampleRoutes keeps events whose route or path matches one of routes.
func SampleSlowRequests ¶
SampleSlowRequests keeps events with duration >= threshold. threshold may be time.Duration, int64 (milliseconds), or int (milliseconds).
func SampleStatusCodes ¶
SampleStatusCodes keeps events whose status code matches one of codes.
func SampleTenants ¶
SampleTenants keeps events whose tenant identifier matches one of ids. It checks both "tenant.id" and "tenant_id".
func SampleUsers ¶
SampleUsers keeps events whose user identifier matches one of ids. It checks both "user.id" and "user_id".
type Schema ¶
Schema controls final output shape for emitted events.
func CustomSchema ¶
CustomSchema creates a schema from a projection function.
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 ¶
SchemaFunc allows mapping an EventView to an output object.
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 HTTPBatchSink ¶
func RotatingFileSink ¶
func RotatingFileSink(cfg RotatingFileConfig) (Sink, error)
RotatingFileSink returns a Sink that rotates log files.
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 ¶
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 )
Source Files
¶
- attr.go
- buffer.go
- builder.go
- canonical.go
- checkpoint.go
- clock.go
- config.go
- config_file.go
- config_options.go
- context.go
- core.go
- dotkey.go
- duplicate.go
- duplicate_policy.go
- encoder.go
- errors.go
- event.go
- event_api.go
- event_builder.go
- http_client.go
- http_context.go
- http_transport.go
- level.go
- logger.go
- metrics.go
- params.go
- pipeline.go
- redactor.go
- sampler.go
- schema.go
- security.go
- sink.go
- spec_contract.go
- standard_sinks.go
- structure.go
- testing_helpers.go
- trace_context.go
- uuidv7.go