loza

package module
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: 9 Imported by: 0

README

LOZA-Go

CI

Status: 🟢 STABLE (v0.4.0) - Production-ready, collector-first stable-v1 SDK

Full emitter SDK conformance is tracked through spec/:

  • spec/docs/SDK_CONFORMANCE_CONTRACT.md
  • spec/docs/SDK_CONFORMANCE_TEST_SUITE.md
  • spec/docs/SDK_COMPLETION_MATRIX.md

LOZA-Go is a canonical wide-event SDK for Go. It builds one structured event per operation (request, job, queue message, CLI run, cron run), then emits to your log/analytics backend.

For the shared event contract, see spec/. For the collector runtime, see collector/. For the operations CLI, see cli/.

slog/zap/zerolog still fit: LOZA is the operation event layer above line-by-line logs.

Install

Core:

go get github.com/astraive/loza/sdks/go

Optional modules:

go get github.com/astraive/loza/sdks/go/middleware
go get github.com/astraive/loza/sdks/go/integrations
go get github.com/astraive/loza/sdks/go/sinks/httpbatch

Quick Start

package main

import (
	"context"

	"github.com/astraive/loza/sdks/go"
)

func main() {
	_ = loza.Configure(loza.Production().WithService("checkout"))
	defer loza.Shutdown(context.Background())

	ctx := loza.StartEvent(context.Background(), loza.Params{
		Event:  "checkout.request",
		Method: "POST",
		Path:   "/checkout",
		Route:  "/checkout",
	})
	defer loza.Emit(ctx)

	loza.Enrich(ctx, loza.UserID("u-1"), loza.String("payment.provider", "stripe"))
	loza.Finish(ctx, "success", loza.Int("status_code", 200))
}

Lifecycle:

StartEvent -> Enrich -> Finish / FinishError -> Emit

Sample event:

{
  "timestamp": "2026-05-11T10:30:00Z",
  "event_id": "evt_abc",
  "request_id": "req_123",
  "trace_id": "trace_456",
  "service": "checkout",
  "event": "checkout.request",
  "method": "POST",
  "path": "/checkout",
  "route": "/checkout",
  "status_code": 200,
  "duration_ms": 42,
  "outcome": "success",
  "user": {
    "id": "u-1"
  },
  "payment": {
    "provider": "stripe"
  }
}

Custom Instances

// Create a custom logger with its own config
logger, _ := loza.CreateLoza(loza.Config{
    Service:      "checkout-api",
    CollectorURL: "http://localhost:9308",
})
logger.Info(ctx, "payment processed")

// Or use the idiomatic Go alias
logger, _ := loza.New(loza.Config{Service: "checkout-api"})
logger.Info(ctx, "payment processed")

// Alias -- same config as default, loza.alias metadata
audit, _ := loza.Alias("audit-service")
audit.Info(ctx, "permission changed")

API Stability (v1)

The stable core surface for v1.0.x is:

  • StartEvent, StartHTTPEvent, StartJobEvent, StartQueueEvent, StartCLIEvent, StartCronEvent
  • Enrich, Set, Merge, Delete
  • Finish, FinishError, Emit, Flush, Shutdown
  • CustomSchema, DuplicateFieldPolicy, Sampler, Redactor, StatsHandler

For cross-language stable-v1 parity, treat docs/sdk-parity-manifest.json as the authoritative shared API surface. Go may still expose language-specific helpers outside that manifest, but those helpers are not part of the cross-language stable-v1 promise unless the manifest is updated.

Package Boundaries

  • github.com/astraive/loza/sdks/go: lifecycle, attrs, config, schema, sampler, security, core sinks.
  • github.com/astraive/loza/sdks/go/middleware/*: HTTP/RPC adapters.
  • github.com/astraive/loza/sdks/go/integrations/*: slog/zap/zerolog/otel bridges.
  • github.com/astraive/loza/sdks/go/sinks/httpbatch: collector HTTP batch transport.
  • github.com/astraive/loza/sdks/go/testkit: capture/assert helpers for tests.

Repository boundaries:

  • spec/: protocol, schemas, compatibility rules
  • collector/: ingest server, worker, durability, fanout, deployment, and heavy sinks
  • cli/: operator and developer CLI

Migration Pattern

  1. Keep existing slog/zap/zerolog.
  2. Add LOZA lifecycle around business operations.
  3. Emit one canonical event per operation for analytics and support workflows.

Examples

Heavy production sinks such as Kafka, ClickHouse, Postgres, DuckDB, OTLP, S3, GCS, and Loki are collector-owned. Applications should emit to the collector using the SDK HTTP batch sink.

Documentation

Breaking Changes in Current Refactor

  • Root testing helpers moved to github.com/astraive/loza/sdks/go/testkit.
  • Root net/http middleware wrapper removed; use github.com/astraive/loza/sdks/go/middleware/nethttp.

Current Focus

  • SDK lifecycle and canonical event emission for Go applications
  • app-side middleware, integrations, and sinks
  • compatibility with the shared LOZA spec and public collector ingest API

SDK Helpers

  • shutdown helpers:
    • loza.ShutdownTimeout(10 * time.Second)
    • loza.MustShutdown(10 * time.Second)
  • config ergonomics:
    • ApplyConfig(...)
    • WithAsyncQueue
    • WithWorkers
    • WithAsyncFlushInterval
    • WithAsyncMaxBatchBytes
    • WithBackpressure
    • WithDuplicatePolicy
    • WithStrict
  • HTTP context propagation:
    • RequestIDFromHTTP
    • TraceFromOTel
    • InjectHTTPHeaders
    • InjectHTTPHeaderCarrier
    • ExtractHTTPHeaders
    • ExtractHTTPHeaderAttrs

WithStrict(true) enables stronger runtime checks for missing service/event, invalid attr keys, canonical key collisions from custom attrs, and unsupported custom values. It also enables strict config validation (Config.Validate / New / Configure) for required service identity and async/security bounds.

Documentation

Overview

Package loza provides canonical wide-event logging for Go services.

Index

Constants

View Source
const (
	LOZA_SPEC_VERSION       = core.LOZA_SPEC_VERSION
	LOZA_INGEST_API_VERSION = core.LOZA_INGEST_API_VERSION
	LOZA_EVENT_VERSION      = core.LOZA_EVENT_VERSION

	LevelDebug  = core.LevelDebug
	LevelInfo   = core.LevelInfo
	LevelNotice = core.LevelNotice
	LevelWarn   = core.LevelWarn
	LevelError  = core.LevelError
	LevelFatal  = core.LevelFatal

	// Backpressure policies
	Block        = core.Block
	DropNewest   = core.DropNewest
	DropOldest   = core.DropOldest
	DropDebug    = core.DropDebug
	DropSampled  = core.DropSampled
	SyncFallback = core.SyncFallback

	// Duplicate field policies
	CanonicalWins    = core.CanonicalWins
	UserWins         = core.UserWins
	FirstWins        = core.FirstWins
	LastWins         = core.LastWins
	KeepBoth         = core.KeepBoth
	ErrorOnDuplicate = core.ErrorOnDuplicate

	// Deprecated aliases — kept for backward compatibility
	//nolint:staticcheck
	AttrWins = core.AttrWins
	//nolint:staticcheck
	AttrsWin = core.AttrsWin
	//nolint:staticcheck
	KeepBothUnderAttrs = core.KeepBothUnderAttrs
	//nolint:staticcheck
	DropDuplicateAttr = core.DropDuplicateAttr

	EventStateCreated          = core.EventStateCreated
	EventStateActive           = core.EventStateActive
	EventStateFinished         = core.EventStateFinished
	EventStateEmitting         = core.EventStateEmitting
	EventStateEmitted          = core.EventStateEmitted
	EventStateInvalid          = core.EventStateInvalid
	EventStateDropped          = core.EventStateDropped
	EventStateEmitFailed       = core.EventStateEmitFailed
	EventStateSpooled          = core.EventStateSpooled
	EventStateDLQWritten       = core.EventStateDLQWritten
	EventStateFailedValidation = core.EventStateFailedValidation
	EventStateDeliveryFailed   = core.EventStateDeliveryFailed
)

Variables

View Source
var (
	// ErrInvalidConfig indicates config validation failure.
	ErrInvalidConfig = core.ErrInvalidConfig
	// ErrConfigFileNotFound is returned when no config file is found.
	ErrConfigFileNotFound = core.ErrConfigFileNotFound
)
View Source
var (
	String   = core.String
	Int      = core.Int
	Int64    = core.Int64
	Uint64   = core.Uint64
	Float    = core.Float64
	Float64  = core.Float64
	Bool     = core.Bool
	Time     = core.Time
	Duration = core.Duration
	Any      = core.Any
	JSON     = core.Any
	Null     = core.Null
	Err      = core.Err
	Stringer = core.Stringer
	Group    = core.Group

	// Canonical fields
	RequestID    = core.RequestID
	TraceID      = core.TraceID
	SpanID       = core.SpanID
	IncidentID   = core.IncidentID
	Service      = core.Service
	Version      = core.Version
	DeploymentID = core.DeploymentID
	Region       = core.Region
	Method       = core.Method
	Path         = core.Path
	Route        = core.Route
	StatusCode   = core.StatusCode
	DurationMS   = core.DurationMS
	Outcome      = core.Outcome

	// Domain fields
	UserID         = core.UserID
	TenantID       = core.TenantID
	WorkspaceID    = core.WorkspaceID
	OrganizationID = core.OrganizationID
	SessionID      = core.SessionID
	OrderID        = core.OrderID
	CartID         = core.CartID
	ProductID      = core.ProductID
	CustomerID     = core.CustomerID
	Plan           = core.Plan
	Currency       = core.Currency
	Amount         = core.Amount
	Country        = core.Country
	Device         = core.Device
	Platform       = core.Platform
	AppVersion     = core.AppVersion
	JobName        = core.JobName
	QueueName      = core.QueueName
	MessageID      = core.MessageID
	Attempt        = core.Attempt
	ErrorType      = core.ErrorType
	ErrorCode      = core.ErrorCode
	ErrorMessage   = core.ErrorMessage
	ErrorStack     = core.ErrorStack
	Retryable      = core.Retryable

	// Sensitive
	MarkSensitive   = core.MarkSensitive
	SensitiveString = core.SensitiveString
	HashString      = core.HashString

	// Additional domain helpers
	PaymentID      = core.PaymentID
	SubscriptionID = core.SubscriptionID
	InvoiceID      = core.InvoiceID
	JobID          = core.JobID
	CorrelationID  = core.CorrelationID
	CommitSha      = core.CommitSha
	Release        = core.Release
	Money          = core.Money
	Percent        = core.Percent
	Bytes          = core.Bytes
	HTTPStatus     = core.HTTPStatus
	Bucket         = core.Bucket
	Tags           = core.Tags
	Masked         = core.Masked
	URL            = core.URL
	EmailHash      = core.EmailHash
	IPHash         = core.IPHash

	// Checkout domain helpers
	CheckoutCartItemCount = core.CheckoutCartItemCount
	CheckoutCartTotal     = core.CheckoutCartTotal
	CheckoutPaymentMethod = core.CheckoutPaymentMethod
	CheckoutStatus        = core.CheckoutStatus

	// Payment domain helpers
	PaymentMethod       = core.PaymentMethod
	PaymentIntentID     = core.PaymentIntentID
	PaymentFailureCode  = core.PaymentFailureCode
	PaymentRetryAttempt = core.PaymentRetryAttempt

	// Billing domain helpers
	BillingPlan           = core.BillingPlan
	BillingSubscriptionID = core.BillingSubscriptionID
	BillingInvoiceID      = core.BillingInvoiceID
	BillingAmount         = core.BillingAmount
	BillingInterval       = core.BillingInterval

	// Agent/AI domain helpers
	AgentName         = core.AgentName
	AgentProvider     = core.AgentProvider
	AgentModel        = core.AgentModel
	AgentRunType      = core.AgentRunType
	AgentToolName     = core.AgentToolName
	AgentToolOutcome  = core.AgentToolOutcome
	AgentInputTokens  = core.AgentInputTokens
	AgentOutputTokens = core.AgentOutputTokens
	AgentCost         = core.AgentCost

	// RAG domain helpers
	RAGIndex            = core.RAGIndex
	RAGEmbeddingModel   = core.RAGEmbeddingModel
	RAGChunksRetrieved  = core.RAGChunksRetrieved
	RAGTopScore         = core.RAGTopScore
	RAGQueryHash        = core.RAGQueryHash
	RAGCitationCount    = core.RAGCitationCount
	RAGRetrievalLatency = core.RAGRetrievalLatency

	// Generic typed attr constructors
	List     = core.List
	Map      = core.Map
	Enum     = core.Enum
	ID       = core.ID
	Hash     = core.Hash
	Redacted = core.Redacted

	// Domain logic
	FeatureFlag     = core.FeatureFlag
	FeatureFlagBool = core.FeatureFlagBool
	Experiment      = core.Experiment

	// Identity
	AccountID = core.AccountID
)

Functions

func Abandon

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

func Add

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

Add appends a value to an array field on the event in ctx.

func Alias

func Alias(service string) (*logger, error)

Alias creates a same-config child Logger that emits loza.alias metadata.

func Append

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

Append appends attrs to the event in ctx.

func AssertEvent

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

AssertEvent checks that ev has the expected value at the given key.

func AssertHasCheckpoint

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

AssertHasCheckpoint checks that ev contains a checkpoint with the given name.

func AssertRedacted

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

AssertRedacted checks that ev has "[REDACTED]" at the given key.

func Audit

func Audit(name string, attrs ...Attr)
func Breadcrumb(name string, attrs ...Attr)

func Cancel

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

func CardinalityPolicy

func CardinalityPolicy(policy map[string]any) map[string]any

func Checkpoint

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

Checkpoint records a named breadcrumb.

func ClearEvents

func ClearEvents(store *MemorySinkStore)

func Configure

func Configure(cfg Config) error

Configure replaces the global default logger with a new one built from cfg.

func ConformanceSuite

func ConformanceSuite() map[string]string

func Count

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

func CreateLoza

func CreateLoza(cfg Config) (*logger, error)

CreateLoza creates a new Logger. Cross-language parity factory.

func Debug

func Debug(msg string, attrs ...Attr)

func DebugContext

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

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

func Default

func Default() *logger

Default returns the global default logger instance.

func Delete

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

Delete removes attrs by key from the event in ctx.

func Drain

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

Drain empties the sink's buffer if it implements Drainable, else flushes.

func Drop

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

func Emit

func Emit(ctx context.Context) error

Emit delivers the event.

func EmitEvent

func EmitEvent(ev *Event) error

EmitEvent delivers an event directly.

func Enrich

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

Enrich appends attrs to the event in ctx.

func EnrichGroup

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

EnrichGroup appends attrs as a named group.

func Error

func Error(msg string, attrs ...Attr)

func ErrorContext

func 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 EventID

func EventID(ctx context.Context) string

EventID returns the ID of the active event in ctx.

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 Fatal

func Fatal(msg string, attrs ...Attr)

func FatalContext

func 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 Finish

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

Finish records outcome and duration.

func FinishError

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

FinishError records error outcome and metadata.

func FinishGroup

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

FinishGroup completes a group handle.

func FinishGroupError

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

FinishGroupError completes a group handle with an error.

func FinishProcess

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

FinishProcess completes a process handle.

func FinishProcessError

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

FinishProcessError completes a process handle with error metadata.

func Flush

func Flush(ctx context.Context) error

Flush drains the queue.

func Gauge

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

func Get

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

Get fetches a value by key (dot-path supported) from event in ctx.

func GetGroup

func GetGroup(ctx context.Context, name string) (map[string]any, bool)

GetGroup fetches a group object from event in ctx.

func GoldenTest

func GoldenTest(path string) string

func HasEvent

func HasEvent(ctx context.Context) bool

HasEvent returns true if ctx contains a LOZA event.

func Health

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

Health checks sink health if it implements Checkable.

func Histogram

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

func IncidentIDFromContext

func IncidentIDFromContext(ctx context.Context) string

IncidentIDFromContext returns the incident ID of the active event.

func Info

func Info(msg string, attrs ...Attr)

func InfoContext

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

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

func InjectHTTPHeaderCarrier

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

InjectHTTPHeaderCarrier injects LOZA + trace headers into a header map.

func InjectHTTPHeaders

func InjectHTTPHeaders(req *http.Request)

InjectHTTPHeaders injects LOZA + trace headers into an outbound request.

func LinkEvent

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

func MemorySink

func MemorySink() (Sink, *MemorySinkStore)

func Merge

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

Merge merges attrs into a named group on the event in ctx.

func Metric

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

func MustShutdown

func MustShutdown(timeout time.Duration)

MustShutdown drains and closes sinks, panicking on error.

func New

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

New creates a new Logger. Idiomatic Go alias for CreateLoza.

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 is the recommended way to create a production SDK client. Requirements: 32.1, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9

func NewRoundTripper

func NewRoundTripper(base http.RoundTripper) http.RoundTripper

func NormalizeEvent

func NormalizeEvent(payload map[string]any) bool

NormalizeEvent normalizes event field aliases in a JSON map payload.

func NormalizeIncidentContext

func NormalizeIncidentContext(ctx *IncidentContext)

Cortex normalization

func NormalizeRemediation

func NormalizeRemediation(r *Remediation)

func NormalizeRemediationFeedback

func NormalizeRemediationFeedback(rf *RemediationFeedback)

func Notice

func Notice(msg string, attrs ...Attr)

func NoticeContext

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

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

func PanicRecoveryEnabled

func PanicRecoveryEnabled() bool

PanicRecoveryEnabled reports whether wrapper helpers recover panics.

func Partial

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

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 RenderPrometheus

func RenderPrometheus(metrics *MetricsCollector) string

RenderPrometheus returns a stable textual metrics endpoint hint for SDK parity.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID of the active event.

func RequestIDFromHTTP

func RequestIDFromHTTP(r *http.Request) string

RequestIDFromHTTP resolves request id from header or active event context.

func Reset

func Reset() error

Reset restores the global default logger to the SDK development preset.

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 Retry

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

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.

func RunHTTP

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

RunHTTP wraps an operation in an HTTP canonical event lifecycle.

func RunJob

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

RunJob wraps an operation in a job canonical event lifecycle.

func RunQueue

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

RunQueue wraps an operation in a queue canonical event lifecycle.

func Security

func Security(name string, attrs ...Attr)

func Set

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

Set upserts attrs on the event in ctx.

func SetDefault

func SetDefault(l *logger)

SetDefault replaces the global default logger instance.

func ShouldSample

func ShouldSample(sampler Sampler, event *Event) bool

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown drains and closes all sinks.

func ShutdownTimeout

func ShutdownTimeout(timeout time.Duration) error

ShutdownTimeout drains and closes sinks with timeout-bound context.

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 of the active event.

func StartCLIEvent

func StartCLIEvent(ctx context.Context, params Params) context.Context

StartCLIEvent starts a CLI execution event.

func StartCron

func StartCron(ctx context.Context, name string) context.Context

StartCron is a convenience wrapper for cron jobs.

func StartCronEvent

func StartCronEvent(ctx context.Context, params Params) context.Context

StartCronEvent starts a cron execution event.

func StartEvent

func StartEvent(ctx context.Context, params Params) context.Context

StartEvent begins a canonical wide event.

func StartHTTPEvent

func StartHTTPEvent(ctx context.Context, params Params) context.Context

StartHTTPEvent starts an event with HTTP defaults.

func StartHTTPEventFromRequest

func StartHTTPEventFromRequest(r *http.Request, params Params) context.Context

StartHTTPEventFromRequest starts an HTTP event using request metadata and propagated headers. It fills Method/Path defaults from r when absent, starts the event, then enriches with extracted request/trace attrs.

func StartJob

func StartJob(ctx context.Context, name string) context.Context

StartJob is a convenience wrapper for named jobs.

func StartJobEvent

func StartJobEvent(ctx context.Context, params Params) context.Context

StartJobEvent starts a background job event.

func StartQueueEvent

func StartQueueEvent(ctx context.Context, params Params) context.Context

StartQueueEvent starts a queue-processing event.

func StartQueueJob

func StartQueueJob(ctx context.Context, queue, messageID string) context.Context

StartQueueJob is a convenience wrapper for queue jobs.

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 StopTimer

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

StopTimer completes a timer handle.

func TraceFromOTel

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

TraceFromOTel returns trace/span ids from OTel span context.

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext returns the trace ID of the active event.

func Track

func Track(name string, attrs ...Attr)

func TryNew

func TryNew(cfg Config) (*logger, error)

TryNew creates a new Logger and returns validation errors instead of panicking.

func ValidateEvent

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

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

func ValidateGraphView

func ValidateGraphView(gv *GraphView) error

func ValidateIncidentContext

func ValidateIncidentContext(ctx *IncidentContext) error

Cortex validation

func ValidateIngestEnvelopeBytes

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

ValidateIngestEnvelopeBytes validates an ingest envelope against the spec contract.

func ValidateRemediation

func ValidateRemediation(r *Remediation) error

func ValidateRemediationFeedback

func ValidateRemediationFeedback(rf *RemediationFeedback) error

func Warn

func Warn(msg string, attrs ...Attr)

func WarnContext

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

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

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 and returns the error.

func WrapHTTPClient

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

Types

type Attr

type Attr = core.Attr

Attr is a typed key-value pair.

func ExtractHTTPHeaderAttrs

func ExtractHTTPHeaderAttrs(header http.Header) []Attr

ExtractHTTPHeaderAttrs extracts common LOZA tracing/request attrs from headers.

func ExtractHTTPHeaders

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

ExtractHTTPHeaders extracts common LOZA tracing/request attrs from inbound headers.

func HTTPMethod

func HTTPMethod(method string) Attr

func HTTPPath

func HTTPPath(path string) Attr

func HTTPReferer

func HTTPReferer(ref string) Attr

func HTTPRequest

func HTTPRequest(r *http.Request) Attr

func HTTPResponse

func HTTPResponse(statusCode int) Attr

func HTTPRoute

func HTTPRoute(route string) Attr

func HTTPUserAgent

func HTTPUserAgent(ua string) Attr

func Measure

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

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

type BackpressurePolicy

type BackpressurePolicy = core.BackpressurePolicy

BackpressurePolicy determines what happens when the async queue is full.

type CollectorClient

type CollectorClient = core.CollectorClient

CollectorClient communicates with the LOZA collector REST API.

func NewCollectorClient

func NewCollectorClient(cfg CollectorClientConfig) *CollectorClient

NewCollectorClient creates a new collector REST API client.

type CollectorClientConfig

type CollectorClientConfig = core.CollectorClientConfig

CollectorClientConfig configures the collector client.

type CollectorSinkConfig

type CollectorSinkConfig = core.CollectorSinkConfig

CollectorSinkConfig configures the collector sink.

type Config

type Config = core.Config

Config is the SDK configuration.

func ApplyConfig

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

ApplyConfig applies options to cfg in order.

func Dev

func Dev() Config

func Disabled

func Disabled() Config

func LoadFromEnv

func LoadFromEnv(base Config) Config

LoadFromEnv loads configuration from environment variables.

func Production

func Production() Config

func SetIDGenerator

func SetIDGenerator(cfg Config, gen IDGenerator) Config

SetIDGenerator replaces the ID generator on a Config for deterministic IDs.

func Test

func Test() Config

type ConfigOption

type ConfigOption = core.ConfigOption

ConfigOption mutates and returns Config.

func WithAPIKey

func WithAPIKey(apiKey string) ConfigOption

func WithAlias

func WithAlias(alias string) ConfigOption

func WithAsync

func WithAsync(enabled bool) ConfigOption

func WithAsyncFlushInterval

func WithAsyncFlushInterval(interval time.Duration) ConfigOption

func WithAsyncMaxBatchBytes

func WithAsyncMaxBatchBytes(maxBytes int) ConfigOption

func WithAsyncQueue

func WithAsyncQueue(size int) ConfigOption

func WithBackpressure

func WithBackpressure(policy BackpressurePolicy) ConfigOption

func WithBatchSize

func WithBatchSize(size int) ConfigOption

func WithCollectorEndpoint

func WithCollectorEndpoint(endpoint string) ConfigOption

func WithCollectorURL

func WithCollectorURL(url string) ConfigOption

func WithCompression

func WithCompression(enabled bool) ConfigOption

func WithConnectionTimeout

func WithConnectionTimeout(timeout time.Duration) ConfigOption

func WithDeploymentID

func WithDeploymentID(deploymentID string) ConfigOption

func WithDuplicatePolicy

func WithDuplicatePolicy(policy DuplicateFieldPolicy) ConfigOption

func WithEncoder

func WithEncoder(encoder Encoder) ConfigOption

func WithEnricher

func WithEnricher(enricher ContextEnricher) ConfigOption

func WithEnvironment

func WithEnvironment(environment string) ConfigOption

func WithEventSchema

func WithEventSchema(schema Schema) ConfigOption

func WithFallbackSink

func WithFallbackSink(sink Sink) ConfigOption

func WithFlushInterval

func WithFlushInterval(interval time.Duration) ConfigOption

func WithIncludeHost

func WithIncludeHost(includeHost bool) ConfigOption

func WithLevel

func WithLevel(level Level) ConfigOption

func WithLogger

func WithLogger(l *logger) ConfigOption

func WithMaxBackoff

func WithMaxBackoff(backoff time.Duration) ConfigOption

func WithMaxBufferSize

func WithMaxBufferSize(size int) ConfigOption

func WithMaxRetries

func WithMaxRetries(retries int) ConfigOption

func WithNamespace

func WithNamespace(namespace string) ConfigOption

func WithOtelBridge

func WithOtelBridge(enabled bool) ConfigOption

func WithPanicRecovery

func WithPanicRecovery(panicRecovery bool) ConfigOption

func WithQueueSize

func WithQueueSize(size int) ConfigOption

func WithRedactor

func WithRedactor(redactor Redactor) ConfigOption

func WithRegion

func WithRegion(region string) ConfigOption

func WithRelease

func WithRelease(release string) ConfigOption

func WithRetry

func WithRetry(maxRetries int) ConfigOption

func WithSampler

func WithSampler(sampler Sampler) ConfigOption

func WithSchema

func WithSchema(schema Schema) ConfigOption

func WithService

func WithService(service string) ConfigOption

func WithSink

func WithSink(sink Sink) ConfigOption

func WithStatsHandler

func WithStatsHandler(handler StatsHandler) ConfigOption

func WithStrict

func WithStrict(strict bool) ConfigOption

func WithTenantID

func WithTenantID(tenantID string) ConfigOption

func WithTimeout

func WithTimeout(timeout time.Duration) ConfigOption

func WithValidateEncoded

func WithValidateEncoded(validate bool) ConfigOption

func WithVersion

func WithVersion(version string) ConfigOption

func WithWorkers

func WithWorkers(workers int) ConfigOption

type ConfigValidationError

type ConfigValidationError = core.ConfigValidationError

ConfigValidationError is returned when config validation fails.

type ContextEnricher

type ContextEnricher = core.ContextEnricher

ContextEnricher derives attrs from context during Emit(ctx).

type CortexClient

type CortexClient = cortex.Client

CortexClient is an HTTP client for the Cortex incident intelligence API.

func NewCortexClient

func NewCortexClient(endpoint string) *CortexClient

NewCortexClient creates an HTTP client for the Cortex incident intelligence API.

type DeliveryFailureHandler

type DeliveryFailureHandler = core.DeliveryFailureHandler

DeliveryFailureHandler receives explicit delivery-failure callbacks.

type DuplicateEmitError

type DuplicateEmitError = core.DuplicateEmitError

DuplicateEmitError is returned when Emit is called after emitted.

type DuplicateFieldError

type DuplicateFieldError = core.DuplicateFieldError

DuplicateFieldError is returned for ErrorOnDuplicate policy violations.

type DuplicateFieldPolicy

type DuplicateFieldPolicy = core.DuplicateFieldPolicy

DuplicateFieldPolicy controls custom attr collisions with canonical fields.

type Encoder

type Encoder = core.Encoder

Encoder serializes events for sink delivery.

type Event

type Event = core.Event

Event is the canonical wide event.

func Capture

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

Capture runs fn and returns all events emitted during execution.

func CloneEvent

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

func CurrentEvent

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

func Events

func Events(store *MemorySinkStore) []*Event

func ExpectEvent

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

ExpectEvent asserts that store contains at least one event and returns it.

func FromContext

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

FromContext retrieves the active Event from ctx.

func LastEvent

func LastEvent(store *MemorySinkStore) *Event

func NewEvent

func NewEvent(params Params) *Event

NewEvent creates a manual event instance.

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.

type EventAlreadyFinishedError

type EventAlreadyFinishedError = core.EventAlreadyFinishedError

EventAlreadyFinishedError is returned when finishing twice.

type EventClosedError

type EventClosedError = core.EventClosedError

EventClosedError is returned when mutating or finishing a closed event.

type EventFunc

type EventFunc = core.EventFunc

EventFunc wraps operation code in lifecycle helpers.

type EventState

type EventState = core.EventState

EventState is the canonical event lifecycle state.

type EventView

type EventView = core.EventView

EventView is a read-only event view for schemas.

type FakeClock

type FakeClock = core.FakeClock

FakeClock implements the Clock interface with a controllable time.

func NewFakeClock

func NewFakeClock(t time.Time) *FakeClock

NewFakeClock creates a new FakeClock for testing.

type FileConfig

type FileConfig = core.FileConfig

FileConfig is the YAML-serializable SDK configuration.

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 and then in ~/.loza/loza.yaml. Requirements: 32.3

type GraphView

type GraphView = cortex.GraphView

GraphView represents a service or incident dependency graph.

type GroupHandle

type GroupHandle = core.GroupHandle

GroupHandle tracks a running group phase.

func StartGroup

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

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

type HTTPBatchSinkConfig

type HTTPBatchSinkConfig = core.HTTPBatchSinkConfig

HTTPBatchSinkConfig configures the HTTP batch sink.

type IDGenerator

type IDGenerator = core.IDGenerator

IDGenerator generates unique string IDs for events.

type IncidentContext

type IncidentContext = cortex.IncidentContext

IncidentContext is the result of incident reconstruction.

type JSONEventEncoder

type JSONEventEncoder = core.JSONEventEncoder

JSONEventEncoder is the default JSON encoder.

func JSONEncoder

func JSONEncoder() *JSONEventEncoder

JSONEncoder returns the default compact JSON encoder.

func PrettyJSONEncoder

func PrettyJSONEncoder() *JSONEventEncoder

PrettyJSONEncoder returns a pretty-print JSON encoder.

type LQLCompilationError added in v0.3.1

type LQLCompilationError = core.LQLCompilationError

LQLCompilationError reports structured LQL compilation failures.

type LQLDiagnostic added in v0.3.1

type LQLDiagnostic = core.LQLDiagnostic

LQLDiagnostic is a structured compiler diagnostic.

type LQLQueryOptions added in v0.3.1

type LQLQueryOptions = core.LQLQueryOptions

LQLQueryOptions controls server-side LQL compilation.

type Level

type Level = core.Level

Level is the log level.

func ParseLevel

func ParseLevel(s string) Level

ParseLevel parses a level string.

type Logger

type Logger = core.Logger

Logger is the public logging pipeline instance type.

type MemorySinkStore

type MemorySinkStore = core.MemorySinkStore

MemorySinkStore holds captured events for testing.

func TestKit

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

TestKit creates a Logger backed by a MemorySink for testing. Spec-aligned alias for TestLogger.

func TestLogger

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

TestLogger creates a Logger backed by a MemorySink for testing.

func Testkit

func Testkit() (*logger, *MemorySinkStore, error)

type MetricsCollector

type MetricsCollector = core.MetricsCollector

MetricsCollector exposes Prometheus metrics for SDK and transport observability.

func NewMetricsCollector

func NewMetricsCollector(namespace string, maxBufferSize int) *MetricsCollector

type MetricsSnapshot

type MetricsSnapshot = map[string]any

MetricsSnapshot is the stable cross-SDK metrics snapshot placeholder.

type MockSink

type MockSink = core.MockSink

MockSink is a test sink that records events.

func NewMockSink

func NewMockSink() *MockSink

NewMockSink creates a new MockSink for testing.

type Params

type Params = core.Params

Params carries metadata to start an event.

type ProcessHandle

type ProcessHandle = core.ProcessHandle

ProcessHandle tracks a running process step.

func Process

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

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

func StartProcess

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

StartProcess is an alias for Process.

type PrometheusStatsHandler

type PrometheusStatsHandler = core.PrometheusStatsHandler

PrometheusStatsHandler wraps a MetricsCollector for StatsHandler integration.

func NewPrometheusStatsHandler

func NewPrometheusStatsHandler(namespace string, maxBufferSize int) *PrometheusStatsHandler

type QueryResult added in v0.3.1

type QueryResult = core.QueryResult

QueryResult contains rows returned by collector queries.

type QueryValue added in v0.3.1

type QueryValue = core.QueryValue

QueryValue is a typed LQL parameter.

type Redactor

type Redactor = core.Redactor

Redactor masks sensitive data.

func ComposeRedactors

func ComposeRedactors(redactors ...Redactor) Redactor

func DefaultRedactor

func DefaultRedactor() Redactor

func DropKeys

func DropKeys(keys ...string) Redactor

func HashKeys

func HashKeys(keys ...string) Redactor

func MaskKeys

func MaskKeys(keys ...string) Redactor

func Redact

func Redact(keys ...string) Redactor

func RedactKeys

func RedactKeys(keys ...string) Redactor

func RedactPatterns

func RedactPatterns(patterns ...string) Redactor

type Remediation

type Remediation = cortex.Remediation

Remediation records a remediation action taken for an incident.

type RemediationFeedback

type RemediationFeedback = cortex.RemediationFeedback

RemediationFeedback records the outcome of a remediation action.

type RotatingFileConfig

type RotatingFileConfig = core.RotatingFileConfig

RotatingFileConfig configures the rotating file sink.

type Sampler

type Sampler = core.Sampler

Sampler decides whether an event should be emitted.

func AllSampler

func AllSampler(samplers ...Sampler) Sampler

func AllowFields

func AllowFields(keys ...string) Sampler

func AnySampler

func AnySampler(samplers ...Sampler) Sampler

func BlockFields

func BlockFields(keys ...string) Sampler

func NotSampler

func NotSampler(sampler Sampler) Sampler

func SampleAll

func SampleAll() Sampler

func SampleByEvent

func SampleByEvent(names ...string) Sampler

func SampleByHeader

func SampleByHeader(header, value string) Sampler

func SampleByOutcome

func SampleByOutcome(outcomes ...string) Sampler

func SampleErrors

func SampleErrors() Sampler

func SampleFeatureFlag

func SampleFeatureFlag(name string, value any) Sampler

func SampleNone

func SampleNone() Sampler

func SampleRandom

func SampleRandom(rate float64) Sampler

func SampleRate

func SampleRate(rate float64) Sampler

func SampleRateLimited

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

func SampleRoutes

func SampleRoutes(routes ...string) Sampler

func SampleSlowRequests

func SampleSlowRequests(d time.Duration) Sampler

func SampleStatusCodes

func SampleStatusCodes(codes ...int) Sampler

func SampleTenants

func SampleTenants(ids ...string) Sampler

func SampleUsers

func SampleUsers(ids ...string) Sampler

type Schema

type Schema = core.Schema

Schema controls final output shape for emitted events.

func CustomSchema

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

func DatadogSchema

func DatadogSchema() Schema

func DefaultSchema

func DefaultSchema() Schema

func ECSchema

func ECSchema() Schema

func FlatSchema

func FlatSchema() Schema

func NestedSchema

func NestedSchema() Schema

func OTelLogSchema

func OTelLogSchema() Schema

func OTelSchema

func OTelSchema() Schema

type SchemaFunc

type SchemaFunc = core.SchemaFunc

SchemaFunc maps EventView to output object.

type SecurityConfig

type SecurityConfig = core.SecurityConfig

SecurityConfig controls event-size and sensitive-data limits.

func MaxAttrLength

func MaxAttrLength(length int) SecurityConfig

func MaxAttrs

func MaxAttrs(count int) SecurityConfig

func MaxEventBytes

func MaxEventBytes(bytes int) SecurityConfig

type Sink

type Sink = core.Sink

Sink is the interface for event destinations.

func CollectorSink

func CollectorSink(cfg CollectorSinkConfig) (Sink, error)

func FileSink

func FileSink(path string) (Sink, error)

func HTTPBatchSink

func HTTPBatchSink(cfg HTTPBatchSinkConfig) (Sink, error)

HTTPBatchSink creates a sink that batches events as NDJSON and flushes to the endpoint when BatchSize is reached or FlushInterval elapses. This is the default sink when CollectorURL is configured.

func KafkaSink

func KafkaSink(endpoint, topic string) (Sink, error)

KafkaSink sends events to the collector with Kafka routing metadata. The collector must have a Kafka sink configured to handle these events.

func LegacyHTTPBatchSink

func LegacyHTTPBatchSink(endpoint string) (Sink, error)

LegacyHTTPBatchSink is a convenience wrapper around 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.

func RotatingFileSink

func RotatingFileSink(cfg RotatingFileConfig) (Sink, error)

func StderrSink

func StderrSink() Sink

func StdoutSink

func StdoutSink() Sink

type StatsHandler

type StatsHandler = core.StatsHandler

StatsHandler receives logger telemetry callbacks.

type StopwatchHandle

type StopwatchHandle = core.StopwatchHandle

StopwatchHandle is a standalone elapsed-time measurer.

func Stopwatch

func Stopwatch() *StopwatchHandle

Stopwatch creates a standalone stopwatch for manual timing.

type TimerHandle

type TimerHandle = core.TimerHandle

TimerHandle tracks a running timer.

func StartTimer

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

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

func Timer

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

Timer is an alias for StartTimer.

Directories

Path Synopsis
examples
config-demo command
state-machine command
src
core
Package core provides internal implementation utilities for LOZA-Go.
Package core provides internal implementation utilities for LOZA-Go.
libs
Package libs hosts shared library helpers for optional adapters.
Package libs hosts shared library helpers for optional adapters.
packages
Package packages groups optional package-level conveniences.
Package packages groups optional package-level conveniences.
testkit
Package testkit provides testing helpers for LOZA event assertions and capture.
Package testkit provides testing helpers for LOZA event assertions and capture.
utils
Package utils hosts utility helpers used by examples and tooling.
Package utils hosts utility helpers used by examples and tooling.

Jump to

Keyboard shortcuts

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