core

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package core provides internal implementation utilities for LOZA-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.
	//
	// Deprecated: Use UserWins.
	AttrWins
	// KeepBothUnderAttrs keeps the canonical value and moves the conflicting
	// attr under an "attrs" key.
	//
	// Deprecated: Use KeepBoth.
	KeepBothUnderAttrs
	// DropDuplicateAttr silently drops the attr (same as CanonicalWins).
	//
	// Deprecated: Use 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.
	//
	// Deprecated: Use UserWins.
	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 (
	LOZA_SPEC_VERSION       = speccontract.LOZASpecVersion
	LOZA_INGEST_API_VERSION = speccontract.LOZAIngestAPIVersion
	LOZA_EVENT_VERSION      = speccontract.LOZAEventVersion
)

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("loza: config file not found")

ErrConfigFileNotFound is returned when no config file is found.

View Source
var ErrInvalidConfig = errors.New("loza: 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 AssertHasCheckpoint

func AssertHasCheckpoint(t testing.TB, ev *Event, name string)

AssertHasCheckpoint asserts the event contains a checkpoint with the given name.

func AssertRedacted

func AssertRedacted(t testing.TB, ev *Event, key string)

AssertRedacted asserts a key on event attrs has the value "[REDACTED]".

func BindEvent

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

BindEvent wraps fn with the event lifecycle, similar to RunEvent but returns directly.

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 Drain

func Drain(ctx context.Context, s Sink) error

Drain calls Drain on a sink if it implements Drainable.

func EventID

func EventID(ctx context.Context) string

EventID returns the event id from ctx when present.

func ExpectAttr

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

ExpectAttr asserts ev contains an attr with the given key and value.

func FinishGroupError

func FinishGroupError(handle *GroupHandle, err error, attrs ...Attr) error

FinishGroupError completes the group with an error status code and error info.

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 Health

func Health(ctx context.Context, s Sink) error

Health checks sink health if it implements Checkable.

func IncidentIDFromContext

func IncidentIDFromContext(ctx context.Context) string

IncidentIDFromContext returns the incident id from ctx when present.

func InjectHTTPHeaderCarrier

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

InjectHTTPHeaderCarrier injects LOZA and trace context into headers.

func InjectHTTPHeaders

func InjectHTTPHeaders(req *http.Request)

InjectHTTPHeaders injects LOZA + 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 Pause

func Pause(s Sink)

Pause pauses a sink if it implements Pauseable.

func Phase

func Phase(ctx context.Context, name string, fn func() error) error

Phase runs fn as a named group phase on the event in ctx.

func QueueSize

func QueueSize(s Sink) int

QueueSize returns the sink's queue size if it implements Sized, or 0.

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 ResetForTest

func ResetForTest()

ResetForTest clears all global mutable state: global logger, clock, and ID generator.

func Resume

func Resume(s Sink)

Resume resumes a paused sink if it implements Pauseable.

func Run

func Run(ctx context.Context, params Params, op Operation, finishAttrs ...Attr) error

Run wraps an operation in the canonical event lifecycle.

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 RunHTTPOp

func RunHTTPOp(ctx context.Context, params Params, op Operation, 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 RunJobOp

func RunJobOp(ctx context.Context, params Params, op Operation, 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 SDKVersion

func SDKVersion() string

SDKVersion returns the SDK version from loza-go.yaml, falling back to the hardcoded default if the file cannot be found or parsed.

func SetDefault

func SetDefault(l *Logger)

SetDefault replaces the global default logger instance.

func SnapshotEvent

func SnapshotEvent(t testing.TB, ev *Event) string

SnapshotEvent returns a JSON snapshot of the event for comparison.

func Span

func Span(ctx context.Context, name string, fn func() error) error

Span runs fn as a named timer span on the event in ctx.

func SpanIDFromContext

func SpanIDFromContext(ctx context.Context) string

SpanIDFromContext returns the span id from ctx when present.

func Step

func Step(ctx context.Context, name string, fn func() error) error

Step runs fn as a named process step on the event in ctx.

func TestKit

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

TestKit creates a logger configured for tests plus its backing memory store. Spec-aligned alias for TestLogger.

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 ValidateEventBytes

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

ValidateEventBytes validates a single event JSON payload against the spec contract.

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 WithGroup

func WithGroup(ctx context.Context, name string, fn func() error, attrs ...Attr) error

WithGroup is an alias for Phase — runs fn as a named group phase.

func WithProcess

func WithProcess(ctx context.Context, name string, fn func() error, attrs ...Attr) error

WithProcess is an alias for Step — runs fn as a named process step.

func WithTimer

func WithTimer(ctx context.Context, name string, fn func() error, attrs ...Attr) error

WithTimer is an alias for Span — runs fn as a named timer span.

func Wrap

func Wrap(name string, fn func() error) error

Wrap wraps fn in a named event lifecycle returning the error.

func WrapHTTPClient

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

WrapHTTPClient wraps an existing client with LOZA 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 AccountID

func AccountID(id string) Attr

AccountID creates a canonical account.id attribute.

func AgentCost

func AgentCost(cost float64) Attr

AgentCost sets agent.cost.

func AgentInputTokens

func AgentInputTokens(tokens int) Attr

AgentInputTokens sets agent.input_tokens.

func AgentModel

func AgentModel(model string) Attr

AgentModel sets agent.model.

func AgentName

func AgentName(name string) Attr

AgentName sets agent.name.

func AgentOutputTokens

func AgentOutputTokens(tokens int) Attr

AgentOutputTokens sets agent.output_tokens.

func AgentProvider

func AgentProvider(provider string) Attr

AgentProvider sets agent.provider.

func AgentRunType

func AgentRunType(runType string) Attr

AgentRunType sets agent.run_type.

func AgentToolName

func AgentToolName(name string) Attr

AgentToolName sets agent.tool_name.

func AgentToolOutcome

func AgentToolOutcome(outcome string) Attr

AgentToolOutcome sets agent.tool_outcome.

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 BillingAmount

func BillingAmount(amount int64) Attr

BillingAmount sets billing.amount.

func BillingInterval

func BillingInterval(interval string) Attr

BillingInterval sets billing.interval.

func BillingInvoiceID

func BillingInvoiceID(id string) Attr

BillingInvoiceID sets billing.invoice_id.

func BillingPlan

func BillingPlan(plan string) Attr

BillingPlan sets billing.plan.

func BillingSubscriptionID

func BillingSubscriptionID(id string) Attr

BillingSubscriptionID sets billing.subscription_id.

func Bool

func Bool(key string, val bool) Attr

Bool creates a bool Attr.

func Bucket

func Bucket(key string, vals ...string) Attr

Bucket creates a bucket/tag grouping attribute.

func Bytes

func Bytes(key string, val int64) Attr

Bytes creates a bytes attribute (int64 byte count).

func CartID

func CartID(id string) Attr

CartID sets cart.id.

func CartTotalCents

func CartTotalCents(total int64) Attr

CartTotalCents sets cart.total_cents.

func CheckoutCartItemCount

func CheckoutCartItemCount(count int) Attr

CheckoutCartItemCount sets checkout.cart_item_count.

func CheckoutCartTotal

func CheckoutCartTotal(total int64) Attr

CheckoutCartTotal sets checkout.cart_total.

func CheckoutPaymentMethod

func CheckoutPaymentMethod(method string) Attr

CheckoutPaymentMethod sets checkout.payment_method.

func CheckoutStatus

func CheckoutStatus(status string) Attr

CheckoutStatus sets checkout.status.

func CommitSha

func CommitSha(sha string) Attr

CommitSha sets commit.sha.

func CorrelationID

func CorrelationID(id string) Attr

CorrelationID sets correlation.id.

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 EmailHash

func EmailHash(key, value string) Attr

EmailHash creates a hashed email attribute.

func Enum

func Enum(key, value string, allowed ...string) Attr

Enum creates an enum attribute with optional allowed values.

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.

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

func HTTPStatus

func HTTPStatus(code int) Attr

HTTPStatus sets http.status (alias for StatusCode).

func Hash

func Hash(key, value string) Attr

Hash creates a hashed attribute.

func HashString

func HashString(key, value string) Attr

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

func ID

func ID(key, value string) Attr

ID creates a high-cardinality ID attribute.

func IPHash

func IPHash(key, value string) Attr

IPHash creates a hashed IP attribute.

func IncidentID

func IncidentID(id string) Attr

IncidentID sets the canonical incident_id field.

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 InvoiceID

func InvoiceID(id string) Attr

InvoiceID sets invoice.id.

func JobID

func JobID(id string) Attr

JobID sets job.id.

func JobName

func JobName(name string) Attr

JobName sets job.name.

func List

func List(key string, values ...any) Attr

List creates a list/array attribute.

func Map

func Map(key string, value map[string]any) Attr

Map creates a map/object attribute.

func MarkSensitive

func MarkSensitive(attr Attr) Attr

MarkSensitive marks attr key as sensitive metadata.

func Masked

func Masked(key, value string) Attr

Masked creates a masked value attribute.

func Measure

func Measure(name string, fn func()) Attr

Measure runs fn, measures its duration, and returns it as an Attr.

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 Money

func Money(key string, amountCents int64, currency string) Attr

Money creates a money attribute with amount in cents and currency.

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 PaymentFailureCode

func PaymentFailureCode(code string) Attr

PaymentFailureCode sets payment.failure_code.

func PaymentID

func PaymentID(id string) Attr

PaymentID sets payment.id.

func PaymentIntentID

func PaymentIntentID(id string) Attr

PaymentIntentID sets payment.intent_id.

func PaymentLatencyMS

func PaymentLatencyMS(ms int64) Attr

PaymentLatencyMS sets payment.latency_ms.

func PaymentMethod

func PaymentMethod(method string) Attr

PaymentMethod sets payment.method.

func PaymentProvider

func PaymentProvider(provider string) Attr

PaymentProvider sets payment.provider.

func PaymentRetryAttempt

func PaymentRetryAttempt(attempt int) Attr

PaymentRetryAttempt sets payment.retry_attempt.

func Percent

func Percent(key string, val float64) Attr

Percent creates a percentage attribute.

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 RAGChunksRetrieved

func RAGChunksRetrieved(count int) Attr

RAGChunksRetrieved sets rag.chunks_retrieved.

func RAGCitationCount

func RAGCitationCount(count int) Attr

RAGCitationCount sets rag.citation_count.

func RAGEmbeddingModel

func RAGEmbeddingModel(model string) Attr

RAGEmbeddingModel sets rag.embedding_model.

func RAGIndex

func RAGIndex(index string) Attr

RAGIndex sets rag.index.

func RAGQueryHash

func RAGQueryHash(hash string) Attr

RAGQueryHash sets rag.query_hash.

func RAGRetrievalLatency

func RAGRetrievalLatency(ms int64) Attr

RAGRetrievalLatency sets rag.retrieval_latency_ms.

func RAGTopScore

func RAGTopScore(score float64) Attr

RAGTopScore sets rag.top_score.

func Redacted

func Redacted(key string) Attr

Redacted creates an explicit redacted marker attribute.

func Region

func Region(region string) Attr

Region sets the canonical region field.

func Release

func Release(version string) Attr

Release sets release.

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 SubscriptionID

func SubscriptionID(id string) Attr

SubscriptionID sets subscription.id.

func Tags

func Tags(key string, vals ...string) Attr

Tags creates a comma-separated tags attribute.

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 URL

func URL(key, value string) Attr

URL creates a URL attribute.

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 Checkable

type Checkable interface {
	Health(ctx context.Context) error
}

Checkable is a sink that reports health.

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 CollectorClient

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

CollectorClient communicates with the LOZA collector REST API.

func NewCollectorClient

func NewCollectorClient(cfg CollectorClientConfig) *CollectorClient

NewCollectorClient creates a new collector client.

func (*CollectorClient) DLQList

func (c *CollectorClient) DLQList(ctx context.Context, filter json.RawMessage) ([]byte, error)

DLQList lists dead-letter queue entries.

func (*CollectorClient) DLQRead

func (c *CollectorClient) DLQRead(ctx context.Context, id string) ([]byte, error)

DLQRead reads a dead-letter queue entry by ID.

func (*CollectorClient) DLQReplay

func (c *CollectorClient) DLQReplay(ctx context.Context, id string) ([]byte, error)

DLQReplay replays a dead-letter queue entry.

func (*CollectorClient) Delete

func (c *CollectorClient) Delete(ctx context.Context, filter json.RawMessage) ([]byte, error)

Delete deletes events from the collector.

func (*CollectorClient) Health

func (c *CollectorClient) Health(ctx context.Context) error

Health checks the collector health endpoint.

func (*CollectorClient) Ingest

func (c *CollectorClient) Ingest(ctx context.Context, events []json.RawMessage) ([]byte, error)

Ingest sends events to the collector for ingestion.

func (*CollectorClient) KeysCreate

func (c *CollectorClient) KeysCreate(ctx context.Context, keyReq json.RawMessage) ([]byte, error)

KeysCreate creates a new API key.

func (*CollectorClient) KeysRevoke

func (c *CollectorClient) KeysRevoke(ctx context.Context, keyID string) ([]byte, error)

KeysRevoke revokes an API key.

func (*CollectorClient) KeysRotate

func (c *CollectorClient) KeysRotate(ctx context.Context, keyID string) ([]byte, error)

func (*CollectorClient) PolicyValidate

func (c *CollectorClient) PolicyValidate(ctx context.Context, policy json.RawMessage) ([]byte, error)

func (*CollectorClient) Query

func (c *CollectorClient) Query(ctx context.Context, query json.RawMessage) ([]byte, error)

Query queries events from the collector.

func (*CollectorClient) QueryLQL

func (c *CollectorClient) QueryLQL(ctx context.Context, lql string, options ...LQLQueryOptions) (*QueryResult, error)

QueryLQL sends LQL source to /lql/query for server-side compilation. Optional options preserve compatibility with callers that only provide source.

func (*CollectorClient) QueryLQLWithOptions added in v0.3.1

func (c *CollectorClient) QueryLQLWithOptions(ctx context.Context, lql string, options LQLQueryOptions) (*QueryResult, error)

QueryLQLWithOptions is an explicit options-form alias for QueryLQL.

func (*CollectorClient) QuerySQL

func (c *CollectorClient) QuerySQL(ctx context.Context, engine, sql string) (*QueryResult, error)

QuerySQL sends a raw SQL query to the collector and returns parsed results.

func (*CollectorClient) Replay

func (c *CollectorClient) Replay(ctx context.Context, request json.RawMessage) ([]byte, error)

Replay replays events through the collector.

func (*CollectorClient) RetentionApply

func (c *CollectorClient) RetentionApply(ctx context.Context, policy json.RawMessage) ([]byte, error)

func (*CollectorClient) SchemaCheck

func (c *CollectorClient) SchemaCheck(ctx context.Context, event json.RawMessage) ([]byte, error)

func (*CollectorClient) SchemaPublish

func (c *CollectorClient) SchemaPublish(ctx context.Context, schema json.RawMessage) ([]byte, error)

func (*CollectorClient) SinksList

func (c *CollectorClient) SinksList(ctx context.Context) ([]byte, error)

SinksList lists configured sinks from the collector.

func (*CollectorClient) SinksTest

func (c *CollectorClient) SinksTest(ctx context.Context, name string) ([]byte, error)

func (*CollectorClient) Tail

func (c *CollectorClient) Tail(ctx context.Context, filter json.RawMessage) ([]byte, error)

Tail tails events from the collector (server-sent events).

func (*CollectorClient) Validate

func (c *CollectorClient) Validate(ctx context.Context, event json.RawMessage) ([]byte, error)

Validate sends an event to the collector for validation without ingesting it.

type CollectorClientConfig

type CollectorClientConfig struct {
	Endpoint      string
	CollectorName string
	Environment   string
	Service       string
	APIKey        string
	BasicUsername string
	BasicPassword string
	Insecure      bool
	Client        *http.Client
}

CollectorClientConfig configures the collector client.

type CollectorSinkConfig

type CollectorSinkConfig struct {
	Endpoint          string
	Headers           map[string]string
	BasicUsername     string
	BasicPassword     string
	Insecure          bool
	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
	Alias        string
	Version      string
	Environment  string
	DeploymentID string
	Region       string
	TenantID     string // Multi-tenant identifier

	// ── Authentication ───────────────────────────────────────────────────────
	APIKey      string // Ingest API key (e.g., "lz_sec_live_k_xxx_yyyy")
	DSNUsername string // Private Basic username or public bearer capability from a DSN.
	DSNPassword string // Basic password; intentionally empty for lz_pub_ DSNs.
	Insecure    bool   // Allow plain HTTP (local dev only). Default: false.

	// ── Collector configuration ───────────────────────────────────────────────
	CollectorURL  string // Credential-free base URL of the LOZA collector (required)
	CollectorName string // Collector slug derived from a loza:// DSN path
	// ── 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
	// OTelBridge enables OpenTelemetry trace context extraction from context.
	// When false (default), TraceFromOTel is skipped to avoid the ~50-100ns context.Value lookup.
	OTelBridge bool
	Security   SecurityConfig
	// Strict enables stronger runtime validation for event shape and attrs.
	Strict bool
	// ValidateEncoded controls post-encode spec contract validation in strict mode.
	// Default: true when Strict is true. Set false for custom schemas
	// (FlatSchema, ECSchema, DatadogSchema) that deviate from LOZA shape.
	ValidateEncoded bool

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

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

Config is the top-level LOZA-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 Disabled

func Disabled() Config

Disabled returns a config preset that disables all output (no-op).

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.

When LOZA_DSN is set, it is parsed first and sets CollectorURL, Environment, Service, and Insecure. Individual env vars (LOZA_COLLECTOR_URL, etc.) override DSN-derived values when both are present.

Supported environment variables:

  • LOZA_DSN: loza:// connection URI (sets CollectorURL, Environment, Service, Insecure)
  • LOZA_COLLECTOR_URL: Collector endpoint URL (overrides DSN)
  • LOZA_SERVICE_NAME: Service name
  • LOZA_SERVICE_VERSION: Service version
  • LOZA_ENVIRONMENT: Deployment environment
  • LOZA_TENANT_ID: Tenant identifier
  • LOZA_BATCH_SIZE: Batch size for event buffering (integer)
  • LOZA_FLUSH_INTERVAL: Flush interval duration (e.g., "5s")
  • LOZA_MAX_BUFFER_SIZE: Maximum buffer size (integer)
  • LOZA_MAX_RETRIES: Maximum retry attempts (integer)
  • LOZA_MAX_BACKOFF: Maximum backoff duration (e.g., "30s")
  • LOZA_TIMEOUT: Request timeout (e.g., "10s")
  • LOZA_CONNECTION_TIMEOUT: Connection timeout (e.g., "5s")
  • LOZA_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 SetIDGenerator

func SetIDGenerator(cfg Config, gen IDGenerator) Config

SetIDGenerator replaces the ID generator on Config for deterministic IDs.

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) WithAPIKey

func (c Config) WithAPIKey(apiKey string) Config

WithAPIKey sets the ingest API key for collector authentication.

func (Config) WithAlias

func (c Config) WithAlias(alias string) Config

WithAlias returns a copy of cfg with the logical loza.alias metadata set.

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) WithBasicAuth added in v0.3.1

func (c Config) WithBasicAuth(username, password string) Config

WithBasicAuth sets the Collector Basic-auth credentials.

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) WithDeploymentID

func (c Config) WithDeploymentID(deploymentID string) Config

WithDeploymentID sets the deployment identifier attached to emitted events.

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) WithIncludeHost

func (c Config) WithIncludeHost(includeHost bool) Config

WithIncludeHost controls whether the host name is attached to emitted events.

func (Config) WithInsecure

func (c Config) WithInsecure(insecure bool) Config

WithInsecure allows plain HTTP connections (for local dev only).

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) WithOTelBridge

func (c Config) WithOTelBridge(enabled bool) Config

WithOTelBridge enables OpenTelemetry trace context extraction from context. When enabled, StartEvent extracts trace_id and span_id from OTel span context. When disabled (default), the OTel context.Value lookup is skipped for performance.

func (Config) WithPanicRecovery

func (c Config) WithPanicRecovery(panicRecovery bool) Config

WithPanicRecovery controls whether lifecycle helpers recover panics.

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) WithValidateEncoded

func (c Config) WithValidateEncoded(validate bool) Config

WithValidateEncoded returns a copy of cfg with ValidateEncoded set.

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 WithAPIKey

func WithAPIKey(apiKey string) ConfigOption

WithAPIKey sets the ingest API key for collector authentication.

func WithAlias

func WithAlias(alias string) ConfigOption

WithAlias applies logical alias metadata without changing service.

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 WithBasicAuth added in v0.3.1

func WithBasicAuth(username, password string) ConfigOption

WithBasicAuth sets Collector Basic-auth credentials. API-key authentication still takes precedence when both are configured.

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 WithCollectorName added in v0.3.1

func WithCollectorName(name string) ConfigOption

WithCollectorName applies the canonical collector slug used for scoped routes.

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 WithDSN

func WithDSN(raw string) ConfigOption

WithDSN parses a loza:// connection URI and applies the resolved values to the config. It retains the credential-free collector base URL and records the required collector slug so the default transport targets canonical /collectors/{collector}/events routes.

Individual config options or env vars applied after WithDSN will override the DSN-derived values.

Example:

config.NewClient(config.Production(),
    config.WithDSN("loza://key-id:key-secret@collector.example/demo?env=prod"),
)

func WithDeploymentID

func WithDeploymentID(deploymentID string) ConfigOption

WithDeploymentID applies a deployment identifier.

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 WithIncludeHost

func WithIncludeHost(includeHost bool) ConfigOption

WithIncludeHost applies host metadata inclusion.

func WithInsecure added in v0.3.1

func WithInsecure(insecure bool) ConfigOption

WithInsecure allows plain HTTP connections for explicitly local development.

func WithLevel

func WithLevel(level Level) ConfigOption

WithLevel applies the minimum log level. Events below this level are dropped.

func WithLogger

func WithLogger(l *Logger) ConfigOption

WithLogger sets a custom logger instance as the parent.

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 WithNamespace

func WithNamespace(namespace string) ConfigOption

WithNamespace sets the logical namespace for the SDK client (multi-tenant).

func WithOtelBridge

func WithOtelBridge(enabled bool) ConfigOption

WithOtelBridge enables or disables OpenTelemetry bridge integration.

func WithPanicRecovery

func WithPanicRecovery(panicRecovery bool) ConfigOption

WithPanicRecovery applies panic recovery behavior.

func WithQueueSize

func WithQueueSize(size int) ConfigOption

WithQueueSize sets the async queue size.

func WithRedactor

func WithRedactor(redactor Redactor) ConfigOption

WithRedactor applies redactor.

func WithRegion

func WithRegion(region string) ConfigOption

WithRegion applies the deployment region.

func WithRelease

func WithRelease(release string) ConfigOption

WithRelease applies the release version (alias for WithVersion).

func WithRetry

func WithRetry(maxRetries int) ConfigOption

WithRetry configures the maximum retry attempts.

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 WithValidateEncoded

func WithValidateEncoded(validate bool) ConfigOption

WithValidateEncoded controls post-encode spec contract validation in strict mode. Default true. Set false for custom schemas that deviate from LOZA shape.

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 Drainable

type Drainable interface {
	Drain(ctx context.Context) error
}

Drain empties the sink's buffer.

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. loza.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
	IncidentID    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
	Processes   []EventProcess
	Groups      []EventGroup
	Timers      []EventTimer
	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 ExpectEvent

func ExpectEvent(t testing.TB, store *MemorySinkStore) *Event

ExpectEvent asserts that store contains at least one event.

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 SanitizeEvent

func SanitizeEvent(ev *Event) *Event

SanitizeEvent clones the event and applies the global config's redactor and security settings. The original event is never mutated.

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) StartGroup

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

StartGroup begins a named group phase and returns a handle to finish it later.

func (*Event) StartProcess

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

StartProcess begins a named process step and returns a handle to finish it later. The step number is auto-incremented per event (1-indexed).

func (*Event) StartTime

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

StartTime returns start time.

func (*Event) StartTimer

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

StartTimer begins a named timer and returns a handle to stop it later.

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 EventGroup

type EventGroup struct {
	Name        string
	StatusCode  int
	StartedAtMS int64
	EndedAtMS   int64
	DurationMS  int64
	Attrs       []Attr
}

EventGroup represents a parent phase containing processes. Groups are recorded in the "groups" array in the emitted JSON.

type EventProcess

type EventProcess struct {
	Step        int
	Name        string
	StatusCode  int
	StartedAtMS int64
	EndedAtMS   int64
	DurationMS  int64
	Attrs       []Attr
}

EventProcess represents a named step in a multi-step process. Processes are recorded in the "processes" array in the emitted JSON.

type EventState

type EventState string
const (
	EventStateCreated          EventState = "created"
	EventStateActive           EventState = "active"
	EventStateFinished         EventState = "finished"
	EventStateEmitting         EventState = "emitting"
	EventStateEmitted          EventState = "emitted"
	EventStateInvalid          EventState = "invalid"
	EventStateDropped          EventState = "dropped"
	EventStateEmitFailed       EventState = "emit_failed"
	EventStateSpooled          EventState = "spooled"
	EventStateDLQWritten       EventState = "dlq_written"
	EventStateFailedValidation EventState = "failed_validation"
	EventStateDeliveryFailed   EventState = "delivery_failed"
)

type EventTimer

type EventTimer struct {
	Name       string
	DurationMS int64
	StatusCode int
	Attrs      []Attr
}

EventTimer represents a named duration measurement. Timers are recorded in the "timers" array in the emitted JSON.

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
	IncidentID() 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
	Processes() []EventProcess
	Groups() []EventGroup
	Timers() []EventTimer
}

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

type FakeClock

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

FakeClock implements the Clock interface with a controllable time.

func NewFakeClock

func NewFakeClock(t time.Time) *FakeClock

func (*FakeClock) Advance

func (c *FakeClock) Advance(d time.Duration)

func (*FakeClock) Now

func (c *FakeClock) Now() time.Time

func (*FakeClock) Set

func (c *FakeClock) Set(t time.Time)

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 loza.yaml file format.

func LoadDefaultsFile

func LoadDefaultsFile() (FileConfig, error)

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

func LoadFromFile

func LoadFromFile(path string) (FileConfig, error)

LoadFromFile loads configuration from a loza.yaml file. If path is empty, it searches for loza.yaml in the current directory, then in the user's home directory (~/.loza/loza.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 GroupHandle

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

GroupHandle is returned by Event.StartGroup and tracks a running group phase.

func (*GroupHandle) Duration

func (h *GroupHandle) Duration() time.Duration

Duration returns the elapsed duration since the group started.

func (*GroupHandle) Finish

func (h *GroupHandle) Finish(attrs ...Attr) error

Finish completes the group with the given attrs.

func (*GroupHandle) FinishError

func (h *GroupHandle) FinishError(statusCode int, attrs ...Attr) error

FinishError completes the group with an error status code.

type HTTPBatchSinkConfig

type HTTPBatchSinkConfig struct {
	Endpoint      string
	Headers       map[string]string
	BasicUsername string
	BasicPassword string
	Insecure      bool
	BatchSize     int
	FlushInterval time.Duration
	Gzip          bool
	Client        *http.Client
	OnError       func(error)
}

HTTPBatchSinkConfig configures the HTTP batch sink.

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 LQLCompilationError added in v0.3.1

type LQLCompilationError struct {
	Message     string          `json:"error,omitempty"`
	Diagnostics []LQLDiagnostic `json:"diagnostics,omitempty"`
	Status      int
}

LQLCompilationError is returned when the collector rejects LQL source.

func (*LQLCompilationError) Error added in v0.3.1

func (e *LQLCompilationError) Error() string

type LQLDiagnostic added in v0.3.1

type LQLDiagnostic struct {
	Code        string            `json:"code,omitempty"`
	Severity    string            `json:"severity,omitempty"`
	Message     string            `json:"message"`
	PrimarySpan json.RawMessage   `json:"primary_span,omitempty"`
	Labels      []json.RawMessage `json:"labels,omitempty"`
}

LQLDiagnostic is a structured compiler diagnostic.

type LQLQueryOptions added in v0.3.1

type LQLQueryOptions struct {
	Parameters map[string]QueryValue
	Limit      int
}

LQLQueryOptions controls server-side LQL compilation and execution.

type LeafValue

type LeafValue struct {
	Kind  uint8 // matches loza.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
	LevelNotice
	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 LOZA-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 loza.yaml file is loaded from the current directory if present.

func (*Logger) Abandon

func (l *Logger) Abandon(ctx context.Context, reason string) error

Abandon marks the event as abandoned with a reason and emits it.

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) Alias

func (l *Logger) Alias(name string) (*Logger, error)

Alias creates an immutable child logger that preserves config and emits loza.alias.

func (*Logger) Append

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

Append appends attrs to the canonical event in ctx.

func (*Logger) Audit

func (l *Logger) Audit(name string, attrs ...Attr)

Audit logs an audit event at info level.

func (*Logger) Breadcrumb

func (l *Logger) Breadcrumb(name string, attrs ...Attr)

Breadcrumb logs a breadcrumb at debug level for tracing user flows.

func (*Logger) Cancel

func (l *Logger) Cancel(ctx context.Context, reason string) error

Cancel marks the event as cancelled with a reason and emits it.

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) CloneEvent

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

CloneEvent clones the event in ctx and returns a standalone copy.

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) Count

func (l *Logger) Count(name string, value int64, attrs ...Attr)

Count logs a count metric at info level.

func (*Logger) CurrentEvent

func (l *Logger) CurrentEvent(ctx context.Context) (*Event, bool)

CurrentEvent returns the active event from ctx.

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) Drop

func (l *Logger) Drop(ctx context.Context, reason string) error

Drop marks the event as dropped with a reason and emits it.

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) Event

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

Event emits a simple success event with optional attrs.

func (*Logger) Fatal

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

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

func (*Logger) FatalContext

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

FatalContext emits an immediate fatal log line with explicit context 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) FinishGroup

func (l *Logger) FinishGroup(h *GroupHandle, attrs ...Attr) error

FinishGroup completes a group handle.

func (*Logger) FinishGroupError

func (l *Logger) FinishGroupError(h *GroupHandle, err error, attrs ...Attr) error

FinishGroupError completes a group handle with error metadata.

func (*Logger) FinishProcess

func (l *Logger) FinishProcess(h *ProcessHandle, attrs ...Attr) error

FinishProcess completes a process handle.

func (*Logger) FinishProcessError

func (l *Logger) FinishProcessError(h *ProcessHandle, err error, statusCode int, attrs ...Attr) error

FinishProcessError completes a process handle with error metadata.

func (*Logger) Flush

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

Flush drains the async queue and flushes all sinks.

func (*Logger) Gauge

func (l *Logger) Gauge(name string, value float64, attrs ...Attr)

Gauge logs a gauge metric at info level.

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) Histogram

func (l *Logger) Histogram(name string, value float64, attrs ...Attr)

Histogram logs a histogram observation at info level.

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) LinkEvent

func (l *Logger) LinkEvent(ctx context.Context, target string, attrs ...Attr) (context.Context, error)

LinkEvent creates a linked child event from the current event in ctx.

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) Metric

func (l *Logger) Metric(name string, value float64, attrs ...Attr)

Metric logs a metric measurement at info level.

func (*Logger) Notice

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

Notice emits an immediate notice log line.

func (*Logger) NoticeContext

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

NoticeContext emits an immediate notice log line with explicit context and event name.

func (*Logger) PanicRecoveryEnabled

func (l *Logger) PanicRecoveryEnabled() bool

PanicRecoveryEnabled reports whether runtime wrappers should recover panics.

func (*Logger) Partial

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

Partial marks the event as partially completed with attrs and emits it.

func (*Logger) Process

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

Process starts a named process step and returns a handle to finish it.

func (*Logger) Retry

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

Retry marks the event for retry with attrs and emits it.

func (*Logger) Security

func (l *Logger) Security(name string, attrs ...Attr)

Security logs a security event at warn level.

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) StartGroup

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

StartGroup starts a named group phase and returns a handle to finish it.

func (*Logger) StartProcess

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

StartProcess is an alias for Process.

func (*Logger) StartTimer

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

StartTimer starts a named timer and returns a handle to stop it.

func (*Logger) StopTimer

func (l *Logger) StopTimer(h *TimerHandle, attrs ...Attr) error

StopTimer completes a timer handle.

func (*Logger) Timer

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

Timer is an alias for StartTimer.

func (*Logger) Track

func (l *Logger) Track(name string, attrs ...Attr)

Track logs a track event at info level.

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 MockSink

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

MockSink is a test sink that records events and supports pausing/draining.

func NewMockSink

func NewMockSink() *MockSink

func (*MockSink) Clear

func (s *MockSink) Clear()

func (*MockSink) Close

func (s *MockSink) Close(_ context.Context) error

func (*MockSink) Events

func (s *MockSink) Events() []*Event

func (*MockSink) Flush

func (s *MockSink) Flush(_ context.Context) error

func (*MockSink) Len

func (s *MockSink) Len() int

func (*MockSink) Name

func (s *MockSink) Name() string

func (*MockSink) Pause

func (s *MockSink) Pause()

Pause pauses the mock sink.

func (*MockSink) Raw

func (s *MockSink) Raw() [][]byte

func (*MockSink) Resume

func (s *MockSink) Resume()

Resume resumes the mock sink.

func (*MockSink) WriteEvent

func (s *MockSink) WriteEvent(_ context.Context, encoded []byte, ev *Event) error

type Operation

type Operation func(ctx context.Context) error

Operation is the unit of work wrapped by core lifecycle helpers.

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
	IncidentID 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 LOZA-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:

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

type Pauseable

type Pauseable interface {
	Pause()
	Resume()
}

Pauseable is a sink that can be paused and resumed.

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 ProcessHandle

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

ProcessHandle is returned by Event.StartProcess and tracks a running process step.

func (*ProcessHandle) Duration

func (h *ProcessHandle) Duration() time.Duration

Duration returns the elapsed duration since the process started.

func (*ProcessHandle) Finish

func (h *ProcessHandle) Finish(attrs ...Attr) error

Finish completes the process with the given attrs.

func (*ProcessHandle) FinishError

func (h *ProcessHandle) FinishError(err error, statusCode int, attrs ...Attr) error

FinishError completes the process with an error status code and error info.

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 QueryResult

type QueryResult struct {
	Columns    []string                 `json:"columns"`
	Rows       []map[string]interface{} `json:"rows"`
	DurationMS int64                    `json:"duration_ms,omitempty"`
	RowCount   int                      `json:"row_count"`
}

QueryResult holds the result of a query against the collector.

type QueryValue added in v0.3.1

type QueryValue struct {
	Type  string `json:"type,omitempty"`
	Value any    `json:"value"`
}

QueryValue is a typed value supplied to an LQL query.

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.

func RedactPatterns

func RedactPatterns(patterns ...string) Redactor

RedactPatterns returns a Redactor that replaces values for keys matching any of the given regex patterns (case-insensitive).

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 AllowFields

func AllowFields(keys ...string) Sampler

AllowFields returns a Sampler that keeps events when the attr list contains any of the specified keys.

func AnySampler

func AnySampler(samplers ...Sampler) Sampler

AnySampler keeps an event if any sampler keeps it.

func BlockFields

func BlockFields(keys ...string) Sampler

BlockFields returns a Sampler that drops events when the attr list contains any of the specified keys.

func NotSampler

func NotSampler(s Sampler) Sampler

NotSampler inverts another sampler.

func SampleAll

func SampleAll() Sampler

SampleAll keeps every event.

func SampleByEvent

func SampleByEvent(names ...string) Sampler

SampleByEvent keeps events whose event name matches one of names.

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 SampleByOutcome

func SampleByOutcome(outcomes ...string) Sampler

SampleByOutcome keeps events whose outcome matches one of outcomes.

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 LOZA 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(cfg HTTPBatchSinkConfig) (Sink, error)

func LegacyHTTPBatchSink

func LegacyHTTPBatchSink(endpoint string) (Sink, error)

LegacyHTTPBatchSink is a convenience wrapper that creates a CollectorSink. Deprecated: Use HTTPBatchSink with HTTPBatchSinkConfig for real batching.

func MultiSink

func MultiSink(sinks ...Sink) Sink

MultiSink fans out events to multiple sinks.

func NoopSink

func NoopSink() Sink

func OTLSink

func OTLSink(endpoint string) (Sink, error)

OTLSink sends events to an OpenTelemetry-compatible endpoint. OTLSink creates an OTLP-compatible sink that forwards events via HTTP batch.

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 loza package from internal/core.

type Sized

type Sized interface {
	QueueSize() int
}

Sized is a sink that reports its queue size.

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 StopwatchHandle

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

StopwatchHandle is a standalone timer that measures elapsed time without an event reference.

func Stopwatch

func Stopwatch() *StopwatchHandle

Stopwatch creates a new standalone stopwatch.

func (*StopwatchHandle) Elapsed

func (h *StopwatchHandle) Elapsed() time.Duration

Elapsed returns the duration since the stopwatch was created.

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
)

type TimerHandle

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

TimerHandle is returned by Event.StartTimer and tracks a running timer.

func (*TimerHandle) Duration

func (h *TimerHandle) Duration() time.Duration

Duration returns the elapsed duration since the timer started.

func (*TimerHandle) Stop

func (h *TimerHandle) Stop(attrs ...Attr) error

Stop completes the timer with the given attrs.

type TraceContext

type TraceContext struct {
	TraceID string
	SpanID  string
}

TraceContext holds trace_id and span_id together for single-generation.

func GenerateTraceContext

func GenerateTraceContext() TraceContext

GenerateTraceContext generates both trace_id and span_id in a single PRNG call. This reduces 2 syscalls to 1 lock+generate operation.

Jump to

Keyboard shortcuts

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