Documentation
¶
Overview ¶
Package core provides internal implementation utilities for LOZA-Go. These types are not part of the public API.
Index ¶
- Constants
- Variables
- func AssertEvent(t testing.TB, ev *Event, key string, expected any)
- func AssertHasCheckpoint(t testing.TB, ev *Event, name string)
- func AssertRedacted(t testing.TB, ev *Event, key string)
- func BindEvent(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func Configure(cfg Config) error
- func Drain(ctx context.Context, s Sink) error
- func EventID(ctx context.Context) string
- func ExpectAttr(t testing.TB, ev *Event, key string, expected any)
- func FinishGroupError(handle *GroupHandle, err error, attrs ...Attr) error
- func GenerateSpanID() string
- func GenerateTraceID() string
- func HasEvent(ctx context.Context) bool
- func Health(ctx context.Context, s Sink) error
- func IncidentIDFromContext(ctx context.Context) string
- func InjectHTTPHeaderCarrier(ctx context.Context, header http.Header) http.Header
- func InjectHTTPHeaders(req *http.Request)
- func IsCanonical(key string) bool
- func IsValidSpanID(spanID string) bool
- func IsValidTraceID(traceID string) bool
- func MemorySink() (Sink, *MemorySinkStore)
- func NewEventMap(in BuildInput) map[string]any
- func NewRoundTripper(base http.RoundTripper) http.RoundTripper
- func NewUUIDv7() string
- func PanicRecoveryEnabled() bool
- func Pause(s Sink)
- func Phase(ctx context.Context, name string, fn func() error) error
- func QueueSize(s Sink) int
- func RequestIDFromContext(ctx context.Context) string
- func RequestIDFromHTTP(r *http.Request) string
- func ResetForTest()
- func Resume(s Sink)
- func Run(ctx context.Context, params Params, op Operation, finishAttrs ...Attr) error
- func RunCLI(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunCron(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunEvent(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunHTTP(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunHTTPOp(ctx context.Context, params Params, op Operation, finishAttrs ...Attr) error
- func RunJob(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func RunJobOp(ctx context.Context, params Params, op Operation, finishAttrs ...Attr) error
- func RunQueue(ctx context.Context, params Params, fn EventFunc, finishAttrs ...Attr) error
- func SDKVersion() string
- func SetDefault(l *Logger)
- func SnapshotEvent(t testing.TB, ev *Event) string
- func Span(ctx context.Context, name string, fn func() error) error
- func SpanIDFromContext(ctx context.Context) string
- func Step(ctx context.Context, name string, fn func() error) error
- func TestKit() (*Logger, *MemorySinkStore, error)
- func TestLogger() (*Logger, *MemorySinkStore, error)
- func TraceFromOTel(ctx context.Context) (traceID string, spanID string)
- func TraceIDFromContext(ctx context.Context) string
- func ValidateEventBytes(raw []byte, strict bool) error
- func ValidateIngestEnvelopeBytes(raw []byte, strict bool) error
- func WithGroup(ctx context.Context, name string, fn func() error, attrs ...Attr) error
- func WithProcess(ctx context.Context, name string, fn func() error, attrs ...Attr) error
- func WithTimer(ctx context.Context, name string, fn func() error, attrs ...Attr) error
- func Wrap(name string, fn func() error) error
- func WrapHTTPClient(client *http.Client) *http.Client
- type AsyncConfig
- type Attr
- func AccountID(id string) Attr
- func AgentCost(cost float64) Attr
- func AgentInputTokens(tokens int) Attr
- func AgentModel(model string) Attr
- func AgentName(name string) Attr
- func AgentOutputTokens(tokens int) Attr
- func AgentProvider(provider string) Attr
- func AgentRunType(runType string) Attr
- func AgentToolName(name string) Attr
- func AgentToolOutcome(outcome string) Attr
- func Amount(value int64) Attr
- func Any(key string, val any) Attr
- func AppVersion(value string) Attr
- func Attempt(n int) Attr
- func BillingAmount(amount int64) Attr
- func BillingInterval(interval string) Attr
- func BillingInvoiceID(id string) Attr
- func BillingPlan(plan string) Attr
- func BillingSubscriptionID(id string) Attr
- func Bool(key string, val bool) Attr
- func Bucket(key string, vals ...string) Attr
- func Bytes(key string, val int64) Attr
- func CartID(id string) Attr
- func CartTotalCents(total int64) Attr
- func CheckoutCartItemCount(count int) Attr
- func CheckoutCartTotal(total int64) Attr
- func CheckoutPaymentMethod(method string) Attr
- func CheckoutStatus(status string) Attr
- func CommitSha(sha string) Attr
- func CorrelationID(id string) Attr
- func Country(code string) Attr
- func Currency(code string) Attr
- func CustomerID(id string) Attr
- func DeploymentID(id string) Attr
- func Device(value string) Attr
- func Duration(key string, val time.Duration) Attr
- func DurationMS(ms int64) Attr
- func EmailHash(key, value string) Attr
- func Enum(key, value string, allowed ...string) Attr
- func Err(err error) Attr
- func ErrorCode(code string) Attr
- func ErrorMessage(msg string) Attr
- func ErrorStack(stack string) Attr
- func ErrorType(name string) Attr
- func Experiment(name, variant string) Attr
- func ExtractHTTPHeaderAttrs(header http.Header) []Attr
- func ExtractHTTPHeaderAttrsWithContext(ctx context.Context, header http.Header) []Attr
- func ExtractHTTPHeaders(r *http.Request) []Attr
- func FeatureFlag(name string, value any) Attr
- func FeatureFlagBool(name string, enabled bool) Attr
- func Float64(key string, val float64) Attr
- func Group(key string, attrs ...Attr) Attr
- func HTTPStatus(code int) Attr
- func Hash(key, value string) Attr
- func HashString(key, value string) Attr
- func ID(key, value string) Attr
- func IPHash(key, value string) Attr
- func IncidentID(id string) Attr
- func Int(key string, val int) Attr
- func Int64(key string, val int64) Attr
- func InvoiceID(id string) Attr
- func JobID(id string) Attr
- func JobName(name string) Attr
- func List(key string, values ...any) Attr
- func Map(key string, value map[string]any) Attr
- func MarkSensitive(attr Attr) Attr
- func Masked(key, value string) Attr
- func Measure(name string, fn func()) Attr
- func MessageID(id string) Attr
- func Method(method string) Attr
- func Money(key string, amountCents int64, currency string) Attr
- func Null(key string) Attr
- func OrderID(id string) Attr
- func OrganizationID(id string) Attr
- func Outcome(outcome string) Attr
- func Path(path string) Attr
- func PaymentFailureCode(code string) Attr
- func PaymentID(id string) Attr
- func PaymentIntentID(id string) Attr
- func PaymentLatencyMS(ms int64) Attr
- func PaymentMethod(method string) Attr
- func PaymentProvider(provider string) Attr
- func PaymentRetryAttempt(attempt int) Attr
- func Percent(key string, val float64) Attr
- func Plan(name string) Attr
- func Platform(value string) Attr
- func ProductID(id string) Attr
- func QueueName(name string) Attr
- func RAGChunksRetrieved(count int) Attr
- func RAGCitationCount(count int) Attr
- func RAGEmbeddingModel(model string) Attr
- func RAGIndex(index string) Attr
- func RAGQueryHash(hash string) Attr
- func RAGRetrievalLatency(ms int64) Attr
- func RAGTopScore(score float64) Attr
- func Redacted(key string) Attr
- func Region(region string) Attr
- func Release(version string) Attr
- func RequestID(id string) Attr
- func Retryable(v bool) Attr
- func Route(route string) Attr
- func SensitiveString(key, value string) Attr
- func Service(service string) Attr
- func SessionID(id string) Attr
- func SpanID(id string) Attr
- func StatusCode(code int) Attr
- func String(key, val string) Attr
- func Stringer(key string, val fmt.Stringer) Attr
- func SubscriptionID(id string) Attr
- func Tags(key string, vals ...string) Attr
- func TenantID(id string) Attr
- func Time(key string, val time.Time) Attr
- func TraceID(id string) Attr
- func URL(key, value string) Attr
- func Uint64(key string, val uint64) Attr
- func UserID(id string) Attr
- func UserSubscription(sub string) Attr
- func Version(version string) Attr
- func WorkspaceID(id string) Attr
- type BackpressurePolicy
- type BatchSinkWriter
- type BuildInput
- type Checkable
- type CheckpointConfig
- type Clock
- type CodedError
- type CollectorClient
- func (c *CollectorClient) DLQList(ctx context.Context, filter json.RawMessage) ([]byte, error)
- func (c *CollectorClient) DLQRead(ctx context.Context, id string) ([]byte, error)
- func (c *CollectorClient) DLQReplay(ctx context.Context, id string) ([]byte, error)
- func (c *CollectorClient) Delete(ctx context.Context, filter json.RawMessage) ([]byte, error)
- func (c *CollectorClient) Health(ctx context.Context) error
- func (c *CollectorClient) Ingest(ctx context.Context, events []json.RawMessage) ([]byte, error)
- func (c *CollectorClient) KeysCreate(ctx context.Context, keyReq json.RawMessage) ([]byte, error)
- func (c *CollectorClient) KeysRevoke(ctx context.Context, keyID string) ([]byte, error)
- func (c *CollectorClient) KeysRotate(ctx context.Context, keyID string) ([]byte, error)
- func (c *CollectorClient) PolicyValidate(ctx context.Context, policy json.RawMessage) ([]byte, error)
- func (c *CollectorClient) Query(ctx context.Context, query json.RawMessage) ([]byte, error)
- func (c *CollectorClient) QueryLQL(ctx context.Context, lql string, options ...LQLQueryOptions) (*QueryResult, error)
- func (c *CollectorClient) QueryLQLWithOptions(ctx context.Context, lql string, options LQLQueryOptions) (*QueryResult, error)
- func (c *CollectorClient) QuerySQL(ctx context.Context, engine, sql string) (*QueryResult, error)
- func (c *CollectorClient) Replay(ctx context.Context, request json.RawMessage) ([]byte, error)
- func (c *CollectorClient) RetentionApply(ctx context.Context, policy json.RawMessage) ([]byte, error)
- func (c *CollectorClient) SchemaCheck(ctx context.Context, event json.RawMessage) ([]byte, error)
- func (c *CollectorClient) SchemaPublish(ctx context.Context, schema json.RawMessage) ([]byte, error)
- func (c *CollectorClient) SinksList(ctx context.Context) ([]byte, error)
- func (c *CollectorClient) SinksTest(ctx context.Context, name string) ([]byte, error)
- func (c *CollectorClient) Tail(ctx context.Context, filter json.RawMessage) ([]byte, error)
- func (c *CollectorClient) Validate(ctx context.Context, event json.RawMessage) ([]byte, error)
- type CollectorClientConfig
- type CollectorSinkConfig
- type Config
- func (c Config) Validate() error
- func (c Config) WithAPIKey(apiKey string) Config
- func (c Config) WithAlias(alias string) Config
- func (c Config) WithAllowPII(allow bool) Config
- func (c Config) WithAsync(enabled bool) Config
- func (c Config) WithAsyncFlushInterval(interval time.Duration) Config
- func (c Config) WithAsyncMaxBatchBytes(maxBytes int) Config
- func (c Config) WithAsyncQueue(size int) Config
- func (c Config) WithBackpressure(policy BackpressurePolicy) Config
- func (c Config) WithBasicAuth(username, password string) Config
- func (c Config) WithCollectorEndpoint(endpoint string) Config
- func (c Config) WithCompression(enabled bool) Config
- func (c Config) WithDeploymentID(deploymentID string) Config
- func (c Config) WithDropOversizedEvents(drop bool) Config
- func (c Config) WithDuplicatePolicy(policy DuplicateFieldPolicy) Config
- func (c Config) WithEncoder(e Encoder) Config
- func (c Config) WithEnricher(fn ContextEnricher) Config
- func (c Config) WithEnvironment(environment string) Config
- func (c Config) WithEventSchema(schema Schema) Config
- func (c Config) WithFallbackSink(sink Sink) Config
- func (c Config) WithIncludeHost(includeHost bool) Config
- func (c Config) WithInsecure(insecure bool) Config
- func (c Config) WithMaxAttrCount(max int) Config
- func (c Config) WithMaxEventBytes(max int) Config
- func (c Config) WithMaxFieldBytes(max int) Config
- func (c Config) WithOTelBridge(enabled bool) Config
- func (c Config) WithPanicRecovery(panicRecovery bool) Config
- func (c Config) WithRedactByDefault(redact bool) Config
- func (c Config) WithRedactor(r Redactor) Config
- func (c Config) WithSampler(s Sampler) Config
- func (c Config) WithSchema(schema Schema) Config
- func (c Config) WithService(service string) Config
- func (c Config) WithSink(sink Sink) Config
- func (c Config) WithStatsHandler(handler StatsHandler) Config
- func (c Config) WithStrict(strict bool) Config
- func (c Config) WithValidateEncoded(validate bool) Config
- func (c Config) WithVersion(version string) Config
- func (c Config) WithWorkers(workers int) Config
- type ConfigOption
- func WithAPIKey(apiKey string) ConfigOption
- func WithAlias(alias string) ConfigOption
- func WithAsync(enabled bool) ConfigOption
- func WithAsyncFlushInterval(interval time.Duration) ConfigOption
- func WithAsyncMaxBatchBytes(maxBytes int) ConfigOption
- func WithAsyncQueue(size int) ConfigOption
- func WithBackpressure(policy BackpressurePolicy) ConfigOption
- func WithBasicAuth(username, password string) ConfigOption
- func WithBatchSize(size int) ConfigOption
- func WithCollectorEndpoint(endpoint string) ConfigOption
- func WithCollectorName(name string) ConfigOption
- func WithCollectorURL(url string) ConfigOption
- func WithCompression(enabled bool) ConfigOption
- func WithConnectionTimeout(timeout time.Duration) ConfigOption
- func WithDSN(raw string) ConfigOption
- func WithDeploymentID(deploymentID string) ConfigOption
- func WithDuplicatePolicy(policy DuplicateFieldPolicy) ConfigOption
- func WithEncoder(encoder Encoder) ConfigOption
- func WithEnricher(enricher ContextEnricher) ConfigOption
- func WithEnvironment(environment string) ConfigOption
- func WithEventSchema(schema Schema) ConfigOption
- func WithFallbackSink(sink Sink) ConfigOption
- func WithFlushInterval(interval time.Duration) ConfigOption
- func WithIncludeHost(includeHost bool) ConfigOption
- func WithInsecure(insecure bool) ConfigOption
- func WithLevel(level Level) ConfigOption
- func WithLogger(l *Logger) ConfigOption
- func WithMaxBackoff(backoff time.Duration) ConfigOption
- func WithMaxBufferSize(size int) ConfigOption
- func WithMaxRetries(retries int) ConfigOption
- func WithNamespace(namespace string) ConfigOption
- func WithOtelBridge(enabled bool) ConfigOption
- func WithPanicRecovery(panicRecovery bool) ConfigOption
- func WithQueueSize(size int) ConfigOption
- func WithRedactor(redactor Redactor) ConfigOption
- func WithRegion(region string) ConfigOption
- func WithRelease(release string) ConfigOption
- func WithRetry(maxRetries int) ConfigOption
- func WithSampler(sampler Sampler) ConfigOption
- func WithSchema(schema Schema) ConfigOption
- func WithService(service string) ConfigOption
- func WithSink(sink Sink) ConfigOption
- func WithStatsHandler(handler StatsHandler) ConfigOption
- func WithStrict(strict bool) ConfigOption
- func WithTenantID(tenantID string) ConfigOption
- func WithTimeout(timeout time.Duration) ConfigOption
- func WithValidateEncoded(validate bool) ConfigOption
- func WithVersion(version string) ConfigOption
- func WithWorkers(workers int) ConfigOption
- type ConfigValidationError
- type ContextEnricher
- type DeliveryFailureHandler
- type DotNode
- type Drainable
- type DuplicateEmitError
- type DuplicateFieldError
- type DuplicateFieldPolicy
- type Encoder
- type ErrorExtractor
- type ErrorInfo
- type Event
- func (e *Event) Add(key string, value interface{}) error
- func (e *Event) AddAttrs(attrs []Attr) error
- func (e *Event) AddCheckpoint(cp EventCheckpoint) error
- func (e *Event) Append(attrs ...Attr) error
- func (e *Event) AttrList() []Attr
- func (e *Event) Checkpoint(name string, attrs ...Attr) error
- func (e *Event) Clone() *Event
- func (e *Event) Delete(keys ...string) error
- func (e *Event) Duration() time.Duration
- func (e *Event) Emit() error
- func (e *Event) Enrich(attrs ...Attr) error
- func (e *Event) Finish(outcome string, attrs ...Attr) error
- func (e *Event) FinishError(err error, attrs ...Attr) error
- func (e *Event) Flush(ctx context.Context) error
- func (e *Event) Get(key string) (any, bool)
- func (e *Event) GetGroup(name string) (map[string]any, bool)
- func (e *Event) ID() string
- func (e *Event) IsEmitted() bool
- func (e *Event) IsFinished() bool
- func (e *Event) MarkEmitted() bool
- func (e *Event) Merge(group string, attrs ...Attr) error
- func (e *Event) MuLock()
- func (e *Event) MuUnlock()
- func (e *Event) Request() string
- func (e *Event) Set(attrs ...Attr) error
- func (e *Event) SetError(info *ErrorInfo)
- func (e *Event) SetLogger(l *Logger)
- func (e *Event) SetOutcome(outcome string)
- func (e *Event) StartGroup(name string, attrs ...Attr) (*GroupHandle, error)
- func (e *Event) StartProcess(name string, attrs ...Attr) (*ProcessHandle, error)
- func (e *Event) StartTime() time.Time
- func (e *Event) StartTimer(name string, attrs ...Attr) (*TimerHandle, error)
- func (e *Event) State() EventState
- func (e *Event) String() string
- func (e *Event) Trace() string
- type EventAlreadyFinishedError
- type EventBuffer
- type EventBufferConfig
- type EventCheckpoint
- type EventClosedError
- type EventFunc
- type EventGroup
- type EventProcess
- type EventState
- type EventTimer
- type EventView
- type FakeClock
- type FieldNamingConfig
- type FileConfig
- type GroupHandle
- type HTTPBatchSinkConfig
- type HTTPResponse
- type HTTPTransport
- type HTTPTransportConfig
- type IDGenerator
- type JSONEventEncoder
- type Kind
- type LQLCompilationError
- type LQLDiagnostic
- type LQLQueryOptions
- type LeafValue
- type Level
- type Logger
- func (l *Logger) Abandon(ctx context.Context, reason string) error
- func (l *Logger) Add(ctx context.Context, key string, value interface{}) error
- func (l *Logger) Alias(name string) (*Logger, error)
- func (l *Logger) Append(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Audit(name string, attrs ...Attr)
- func (l *Logger) Breadcrumb(name string, attrs ...Attr)
- func (l *Logger) Cancel(ctx context.Context, reason string) error
- func (l *Logger) Checkpoint(ctx context.Context, name string, attrs ...Attr) error
- func (l *Logger) Child(options ...ConfigOption) (*Logger, error)
- func (l *Logger) CloneEvent(ctx context.Context) (*Event, error)
- func (l *Logger) Close() error
- func (l *Logger) Config() Config
- func (l *Logger) Count(name string, value int64, attrs ...Attr)
- func (l *Logger) CurrentEvent(ctx context.Context) (*Event, bool)
- func (l *Logger) Debug(msg string, attrs ...Attr)
- func (l *Logger) DebugContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) Delete(ctx context.Context, keys ...string) error
- func (l *Logger) Drop(ctx context.Context, reason string) error
- func (l *Logger) Emit(ctx context.Context) error
- func (l *Logger) EmitEvent(ev *Event) error
- func (l *Logger) EmitEventWithContext(ctx context.Context, ev *Event) error
- func (l *Logger) Enrich(ctx context.Context, attrs ...Attr) error
- func (l *Logger) EnrichGroup(ctx context.Context, key string, attrs ...Attr) error
- func (l *Logger) Error(msg string, attrs ...Attr)
- func (l *Logger) ErrorContext(ctx context.Context, msg string, err error, event string, attrs ...Attr)
- func (l *Logger) Event(ctx context.Context, name string, attrs ...Attr) error
- func (l *Logger) Fatal(msg string, attrs ...Attr)
- func (l *Logger) FatalContext(ctx context.Context, msg string, err error, event string, attrs ...Attr)
- func (l *Logger) Finish(ctx context.Context, outcome string, attrs ...Attr) error
- func (l *Logger) FinishError(ctx context.Context, err error, attrs ...Attr) error
- func (l *Logger) FinishGroup(h *GroupHandle, attrs ...Attr) error
- func (l *Logger) FinishGroupError(h *GroupHandle, err error, attrs ...Attr) error
- func (l *Logger) FinishProcess(h *ProcessHandle, attrs ...Attr) error
- func (l *Logger) FinishProcessError(h *ProcessHandle, err error, statusCode int, attrs ...Attr) error
- func (l *Logger) Flush(ctx context.Context) error
- func (l *Logger) Gauge(name string, value float64, attrs ...Attr)
- func (l *Logger) Get(ctx context.Context, key string) (any, bool)
- func (l *Logger) GetGroup(ctx context.Context, key string) (map[string]any, bool)
- func (l *Logger) Histogram(name string, value float64, attrs ...Attr)
- func (l *Logger) Info(msg string, attrs ...Attr)
- func (l *Logger) InfoContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) LinkEvent(ctx context.Context, target string, attrs ...Attr) (context.Context, error)
- func (l *Logger) Merge(ctx context.Context, group string, attrs ...Attr) error
- func (l *Logger) Metric(name string, value float64, attrs ...Attr)
- func (l *Logger) Notice(msg string, attrs ...Attr)
- func (l *Logger) NoticeContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) PanicRecoveryEnabled() bool
- func (l *Logger) Partial(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Process(ctx context.Context, name string, attrs ...Attr) (*ProcessHandle, error)
- func (l *Logger) Retry(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Security(name string, attrs ...Attr)
- func (l *Logger) Set(ctx context.Context, attrs ...Attr) error
- func (l *Logger) Shutdown(ctx context.Context) error
- func (l *Logger) StartEvent(ctx context.Context, params Params) context.Context
- func (l *Logger) StartGroup(ctx context.Context, name string, attrs ...Attr) (*GroupHandle, error)
- func (l *Logger) StartProcess(ctx context.Context, name string, attrs ...Attr) (*ProcessHandle, error)
- func (l *Logger) StartTimer(ctx context.Context, name string, attrs ...Attr) (*TimerHandle, error)
- func (l *Logger) StopTimer(h *TimerHandle, attrs ...Attr) error
- func (l *Logger) Timer(ctx context.Context, name string, attrs ...Attr) (*TimerHandle, error)
- func (l *Logger) Track(name string, attrs ...Attr)
- func (l *Logger) Warn(msg string, attrs ...Attr)
- func (l *Logger) WarnContext(ctx context.Context, msg, event string, attrs ...Attr)
- func (l *Logger) WithSchema(schema Schema) (*Logger, error)
- type MemorySinkStore
- type MetricsCollector
- func (mc *MetricsCollector) Handler() http.Handler
- func (mc *MetricsCollector) ObserveEmitDuration(duration time.Duration)
- func (mc *MetricsCollector) OnBackpressure()
- func (mc *MetricsCollector) OnEventCreated()
- func (mc *MetricsCollector) OnEventDropped(reason string)
- func (mc *MetricsCollector) OnEventEmitted(success bool)
- func (mc *MetricsCollector) OnEventFinished()
- func (mc *MetricsCollector) OnRetry(attempt int)
- func (mc *MetricsCollector) Registry() *prometheus.Registry
- func (mc *MetricsCollector) SetBufferSize(size int)
- type MockSink
- func (s *MockSink) Clear()
- func (s *MockSink) Close(_ context.Context) error
- func (s *MockSink) Events() []*Event
- func (s *MockSink) Flush(_ context.Context) error
- func (s *MockSink) Len() int
- func (s *MockSink) Name() string
- func (s *MockSink) Pause()
- func (s *MockSink) Raw() [][]byte
- func (s *MockSink) Resume()
- func (s *MockSink) WriteEvent(_ context.Context, encoded []byte, ev *Event) error
- type Operation
- type Params
- type Pauseable
- type Pipeline
- type PipelineConfig
- type PipelineItem
- type ProcessHandle
- type PrometheusStatsHandler
- func (h *PrometheusStatsHandler) Handler() http.Handler
- func (h *PrometheusStatsHandler) Metrics() *MetricsCollector
- func (h *PrometheusStatsHandler) ObserveEmitDuration(d time.Duration)
- func (h *PrometheusStatsHandler) OnDeliveryFailed(_ *Event, _ error)
- func (h *PrometheusStatsHandler) OnDrop(reason string)
- func (h *PrometheusStatsHandler) OnEmit(ev *Event)
- func (h *PrometheusStatsHandler) OnError(err error)
- func (h *PrometheusStatsHandler) OnEventCreated()
- func (h *PrometheusStatsHandler) OnEventFinished()
- type QueryResult
- type QueryValue
- type Redactor
- type RetriableError
- type RotatingFileConfig
- type Sampler
- func AllSampler(samplers ...Sampler) Sampler
- func AllowFields(keys ...string) Sampler
- func AnySampler(samplers ...Sampler) Sampler
- func BlockFields(keys ...string) Sampler
- func NotSampler(s Sampler) Sampler
- func SampleAll() Sampler
- func SampleByEvent(names ...string) Sampler
- func SampleByHeader(header, value string) Sampler
- func SampleByOutcome(outcomes ...string) Sampler
- func SampleErrors() Sampler
- func SampleFeatureFlag(name string, value any) Sampler
- func SampleNone() Sampler
- func SampleRandom(rate float64) Sampler
- func SampleRateLimited(rate float64, window time.Duration) Sampler
- func SampleRoutes(routes ...string) Sampler
- func SampleSlowRequests(threshold any) Sampler
- func SampleStatusCodes(codes ...int) Sampler
- func SampleTenants(ids ...string) Sampler
- func SampleUsers(ids ...string) Sampler
- type Schema
- type SchemaFunc
- type SecurityConfig
- type Sink
- func CollectorSink(cfg CollectorSinkConfig) (Sink, error)
- func FileSink(path string) (Sink, error)
- func HTTPBatchSink(cfg HTTPBatchSinkConfig) (Sink, error)
- func LegacyHTTPBatchSink(endpoint string) (Sink, error)
- func MultiSink(sinks ...Sink) Sink
- func NoopSink() Sink
- func OTLSink(endpoint string) (Sink, error)
- func RotatingFileSink(cfg RotatingFileConfig) (Sink, error)
- func StderrSink() Sink
- func StdoutSink() Sink
- type SinkWriter
- type Sized
- type StackError
- type StatsHandler
- type StopwatchHandle
- type TimeFormat
- type TimerHandle
- type TraceContext
Constants ¶
const ( // CanonicalWins keeps the canonical value and silently drops the attr (default). CanonicalWins DuplicateFieldPolicy = iota // AttrWins overwrites the canonical field with the attr value. // // 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 )
const ( LOZA_SPEC_VERSION = speccontract.LOZASpecVersion LOZA_INGEST_API_VERSION = speccontract.LOZAIngestAPIVersion LOZA_EVENT_VERSION = speccontract.LOZAEventVersion )
Variables ¶
var CanonicalFieldSet = speccontract.CanonicalFieldSet
CanonicalFieldSet is the generated set of top-level canonical JSON field names.
var ErrConfigFileNotFound = errors.New("loza: config file not found")
ErrConfigFileNotFound is returned when no config file is found.
var ErrInvalidConfig = errors.New("loza: invalid config")
ErrInvalidConfig is returned when configuration validation fails.
var ErrPipelineClosed = errors.New("pipeline closed")
ErrPipelineClosed is returned when enqueueing after shutdown starts.
Functions ¶
func AssertEvent ¶
AssertEvent asserts a key on event attrs equals expected.
func AssertHasCheckpoint ¶
AssertHasCheckpoint asserts the event contains a checkpoint with the given name.
func AssertRedacted ¶
AssertRedacted asserts a key on event attrs has the value "[REDACTED]".
func BindEvent ¶
BindEvent wraps fn with the event lifecycle, similar to RunEvent but returns directly.
func Configure ¶
Configure replaces the global default logger with a new one built from cfg. The previous default logger is drained/shutdown to avoid losing queued events.
func ExpectAttr ¶
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 IncidentIDFromContext ¶
IncidentIDFromContext returns the incident id from ctx when present.
func InjectHTTPHeaderCarrier ¶
InjectHTTPHeaderCarrier injects LOZA and trace context into headers.
func InjectHTTPHeaders ¶
InjectHTTPHeaders injects LOZA + trace context headers into an outbound request.
func IsCanonical ¶
IsCanonical returns true if key matches a canonical field name.
func IsValidSpanID ¶
IsValidSpanID checks if a span ID is valid according to W3C Trace Context spec. Valid span IDs are 16 hex characters and not all zeros.
func IsValidTraceID ¶
IsValidTraceID checks if a trace ID is valid according to W3C Trace Context spec. Valid trace IDs are 32 hex characters and not all zeros.
func MemorySink ¶
func MemorySink() (Sink, *MemorySinkStore)
func NewEventMap ¶
func NewEventMap(in BuildInput) map[string]any
NewEventMap builds a canonical map representation used by optional internal paths.
func NewRoundTripper ¶
func NewRoundTripper(base http.RoundTripper) http.RoundTripper
NewRoundTripper wraps a base transport and enriches active events with outbound HTTP metadata.
func NewUUIDv7 ¶
func NewUUIDv7() string
NewUUIDv7 generates a new UUIDv7 string using the global generator. IDs are monotonically increasing within the same millisecond.
func PanicRecoveryEnabled ¶
func PanicRecoveryEnabled() bool
PanicRecoveryEnabled reports whether the default logger recovers panics in wrappers.
func RequestIDFromContext ¶
RequestIDFromContext returns the request id from ctx when present.
func RequestIDFromHTTP ¶
RequestIDFromHTTP resolves request id from header, then active event context.
func ResetForTest ¶
func ResetForTest()
ResetForTest clears all global mutable state: global logger, clock, and ID generator.
func RunEvent ¶
RunEvent wraps an operation in the canonical lifecycle: StartEvent -> fn -> Finish/FinishError -> Emit.
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 ¶
SnapshotEvent returns a JSON snapshot of the event for comparison.
func SpanIDFromContext ¶
SpanIDFromContext returns the span id from ctx when present.
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 ¶
TraceFromOTel returns trace and span ids from the current OTel span context.
func TraceIDFromContext ¶
TraceIDFromContext returns the trace id from ctx when present.
func ValidateEventBytes ¶
ValidateEventBytes validates a single event JSON payload against the spec contract.
func ValidateIngestEnvelopeBytes ¶
ValidateIngestEnvelopeBytes validates a runtime envelope payload against the generated contract before it is sent to the collector.
func WithProcess ¶
WithProcess is an alias for Step — runs fn as a named process step.
Types ¶
type AsyncConfig ¶
type AsyncConfig struct {
// Enabled turns on async mode. Default: true in Production(), false in Dev().
Enabled bool
// QueueSize is the channel depth. Default: 8192.
QueueSize int
// Workers is the number of goroutines draining the queue. Default: 4.
Workers int
// FlushInterval is how often buffered sinks are flushed. Default: 1s.
FlushInterval time.Duration
// MaxBatchBytes caps the byte size of each sink batch. Default: 4MB.
MaxBatchBytes int
// Backpressure controls what happens when the queue is full. Default: Block.
Backpressure BackpressurePolicy
}
AsyncConfig configures the background async emit pipeline.
type Attr ¶
Attr is a typed key-value pair used to enrich canonical events. Canonical fields use Kind to skip reflection on the fast path.
func AgentInputTokens ¶
AgentInputTokens sets agent.input_tokens.
func AgentOutputTokens ¶
AgentOutputTokens sets agent.output_tokens.
func AgentToolOutcome ¶
AgentToolOutcome sets agent.tool_outcome.
func BillingInterval ¶
BillingInterval sets billing.interval.
func BillingInvoiceID ¶
BillingInvoiceID sets billing.invoice_id.
func BillingSubscriptionID ¶
BillingSubscriptionID sets billing.subscription_id.
func CheckoutCartItemCount ¶
CheckoutCartItemCount sets checkout.cart_item_count.
func CheckoutCartTotal ¶
CheckoutCartTotal sets checkout.cart_total.
func CheckoutPaymentMethod ¶
CheckoutPaymentMethod sets checkout.payment_method.
func DeploymentID ¶
DeploymentID sets the canonical deployment_id field.
func Experiment ¶
Experiment adds an experiment variant field.
func ExtractHTTPHeaderAttrs ¶
ExtractHTTPHeaderAttrs converts common tracing/request headers into attrs.
func ExtractHTTPHeaderAttrsWithContext ¶
ExtractHTTPHeaderAttrsWithContext converts common tracing/request headers into attrs.
func ExtractHTTPHeaders ¶
ExtractHTTPHeaders converts common tracing/request headers into attrs.
func FeatureFlag ¶
FeatureFlag adds a feature flag entry under the feature group.
func FeatureFlagBool ¶
FeatureFlagBool adds a boolean feature flag.
func Group ¶
Group creates a nested object Attr.
loza.Group("user", loza.String("id", uid), loza.String("plan", "pro"))
→ {"user":{"id":"...","plan":"pro"}}
func HTTPStatus ¶
HTTPStatus sets http.status (alias for StatusCode).
func HashString ¶
HashString stores a hash-ready marker field for sensitive values.
func MarkSensitive ¶
MarkSensitive marks attr key as sensitive metadata.
func PaymentFailureCode ¶
PaymentFailureCode sets payment.failure_code.
func PaymentLatencyMS ¶
PaymentLatencyMS sets payment.latency_ms.
func PaymentProvider ¶
PaymentProvider sets payment.provider.
func PaymentRetryAttempt ¶
PaymentRetryAttempt sets payment.retry_attempt.
func RAGChunksRetrieved ¶
RAGChunksRetrieved sets rag.chunks_retrieved.
func RAGCitationCount ¶
RAGCitationCount sets rag.citation_count.
func RAGEmbeddingModel ¶
RAGEmbeddingModel sets rag.embedding_model.
func RAGRetrievalLatency ¶
RAGRetrievalLatency sets rag.retrieval_latency_ms.
func SensitiveString ¶
SensitiveString marks a string field as sensitive.
func UserSubscription ¶
UserSubscription sets user.subscription.
type BackpressurePolicy ¶
type BackpressurePolicy int
BackpressurePolicy determines what happens when the async queue is full.
const ( // Block waits until space is available (default — protects against data loss). Block BackpressurePolicy = iota // DropNewest drops the incoming event when the queue is full. DropNewest // DropOldest discards the oldest queued event to make room. DropOldest // DropDebug drops debug-level events first under pressure. DropDebug // DropSampled drops sampled (non-error) events first. DropSampled // SyncFallback writes synchronously to sinks if the queue is full. SyncFallback )
type BatchSinkWriter ¶
type BatchSinkWriter interface {
WriteBatch(ctx context.Context, items []PipelineItem) error
}
BatchSinkWriter optionally accepts a batch of pipeline items in one call.
type BuildInput ¶
type BuildInput struct {
Timestamp time.Time
EventID string
RequestID string
TraceID string
SpanID string
ParentID string
Level string
Event string
Message string
Outcome string
Service string
Version string
Environment string
Method string
Path string
Route string
StatusCode int
DurationMS int64
}
BuildInput contains normalized values used to construct a canonical event map.
type CheckpointConfig ¶
type CheckpointConfig struct {
// Enabled allows checkpoints to be recorded. Default: true.
Enabled bool
// EmitImmediately emits each checkpoint as a standalone log line in
// addition to including it in the final event. Default: false.
EmitImmediately bool
// MaxCheckpoints caps how many checkpoints are stored per event. Default: 32.
MaxCheckpoints int
}
CheckpointConfig controls checkpoint behaviour.
type Clock ¶
Clock abstracts time to allow deterministic testing.
func NewMockClock ¶
NewMockClock returns a Clock that always returns t.
type CodedError ¶
type CodedError interface {
Code() string
}
CodedError is implemented by errors that carry a machine-readable code.
type 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) 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 ¶
KeysRevoke revokes an API key.
func (*CollectorClient) KeysRotate ¶
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) 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 ¶
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 ¶
Validate validates cfg and returns explicit field-level errors. In strict mode, additional config checks are enforced.
func (Config) WithAPIKey ¶
WithAPIKey sets the ingest API key for collector authentication.
func (Config) WithAllowPII ¶
WithAllowPII enables or disables PII exposure when RedactByDefault is true.
func (Config) WithAsyncFlushInterval ¶
WithAsyncFlushInterval sets async flush interval and enables async mode.
func (Config) WithAsyncMaxBatchBytes ¶
WithAsyncMaxBatchBytes sets async max batch size and enables async mode.
func (Config) WithAsyncQueue ¶
WithAsyncQueue sets async queue size and enables async mode.
func (Config) WithBackpressure ¶
func (c Config) WithBackpressure(policy BackpressurePolicy) Config
WithBackpressure sets async backpressure policy.
func (Config) WithBasicAuth ¶ added in v0.3.1
WithBasicAuth sets the Collector Basic-auth credentials.
func (Config) WithCollectorEndpoint ¶
func (Config) WithCompression ¶
WithCompression enables or disables gzip compression for collector requests.
func (Config) WithDeploymentID ¶
WithDeploymentID sets the deployment identifier attached to emitted events.
func (Config) WithDropOversizedEvents ¶
WithDropOversizedEvents enables or disables dropping of events that exceed max_event_bytes.
func (Config) WithDuplicatePolicy ¶
func (c Config) WithDuplicatePolicy(policy DuplicateFieldPolicy) Config
WithDuplicatePolicy sets duplicate field conflict policy.
func (Config) WithEncoder ¶
WithEncoder sets the encoder.
func (Config) WithEnricher ¶
func (c Config) WithEnricher(fn ContextEnricher) Config
WithEnricher sets a context enricher hook that runs during Emit(ctx).
func (Config) WithEnvironment ¶
WithEnvironment returns a copy of cfg with Environment set.
func (Config) WithEventSchema ¶
WithEventSchema sets the output event schema.
func (Config) WithFallbackSink ¶
WithFallbackSink configures a sink used when primary sink writes fail.
func (Config) WithIncludeHost ¶
WithIncludeHost controls whether the host name is attached to emitted events.
func (Config) WithInsecure ¶
WithInsecure allows plain HTTP connections (for local dev only).
func (Config) WithMaxAttrCount ¶
WithMaxAttrCount sets the maximum number of attributes per event.
func (Config) WithMaxEventBytes ¶
WithMaxEventBytes sets the maximum byte size for entire events.
func (Config) WithMaxFieldBytes ¶
WithMaxFieldBytes sets the maximum byte size for individual field values.
func (Config) WithOTelBridge ¶
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 ¶
WithPanicRecovery controls whether lifecycle helpers recover panics.
func (Config) WithRedactByDefault ¶
WithRedactByDefault enables or disables redaction of sensitive fields by default.
func (Config) WithRedactor ¶
WithRedactor sets the redactor.
func (Config) WithSampler ¶
WithSampler sets the sampler.
func (Config) WithSchema ¶
WithSchema sets the output event schema.
func (Config) WithService ¶
WithService returns a copy of cfg with Service set.
func (Config) WithStatsHandler ¶
func (c Config) WithStatsHandler(handler StatsHandler) Config
WithStatsHandler sets callbacks for emit/drop/error telemetry.
func (Config) WithStrict ¶
WithStrict enables or disables strict mode validation.
func (Config) WithValidateEncoded ¶
WithValidateEncoded returns a copy of cfg with ValidateEncoded set.
func (Config) WithVersion ¶
WithVersion returns a copy of cfg with Version set.
func (Config) WithWorkers ¶
WithWorkers sets async worker count and enables async mode.
type ConfigOption ¶
ConfigOption mutates and returns a Config.
func 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 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 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 WithStatsHandler ¶
func WithStatsHandler(handler StatsHandler) ConfigOption
WithStatsHandler applies stats handler callbacks.
func WithTenantID ¶
func WithTenantID(tenantID string) ConfigOption
WithTenantID applies the tenant ID.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ConfigOption
WithTimeout applies the request timeout.
func 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 WithWorkers ¶
func WithWorkers(workers int) ConfigOption
WithWorkers applies async worker count.
type ConfigValidationError ¶
ConfigValidationError is returned when a specific config field is invalid.
func (*ConfigValidationError) Error ¶
func (e *ConfigValidationError) Error() string
func (*ConfigValidationError) Unwrap ¶
func (e *ConfigValidationError) Unwrap() error
type ContextEnricher ¶
ContextEnricher appends attrs derived from request/job context during Emit.
type DeliveryFailureHandler ¶
DeliveryFailureHandler is an optional extension for StatsHandler implementations that want explicit delivery-failure callbacks.
type DotNode ¶
type DotNode struct {
// Value holds the leaf attr value (Kind, Value) when Children is nil.
Value *LeafValue
// Children maps sub-key → child node.
Children map[string]*DotNode
}
DotNode is an intermediate tree node used to merge dot-key attrs (e.g. "user.id", "user.name") into nested JSON objects.
func ExpandDotKeys ¶
func ExpandDotKeys(keys []string, kinds []uint8, values []any) ( plainKeys []string, plainKinds []uint8, plainValues []any, groupKeys []string, groupRoots []*DotNode, )
ExpandDotKeys takes a flat list of (key, kind, value) tuples and converts all dot-separated keys into a nested tree. Non-dot keys are left as-is.
Returns two slices:
- plain: attrs whose keys have no dot (or dot expansion is disabled)
- groups: map[topKey]*DotNode for merged nested objects
type DuplicateEmitError ¶
type DuplicateEmitError struct {
EventID string
}
DuplicateEmitError is returned when Emit is called after an event has already reached the emitted terminal state.
func (*DuplicateEmitError) Error ¶
func (e *DuplicateEmitError) Error() string
type DuplicateFieldError ¶
type DuplicateFieldError struct {
Key string
}
DuplicateFieldError is returned when duplicate canonical attrs are rejected by DuplicateFieldPolicy=ErrorOnDuplicate.
func (*DuplicateFieldError) Error ¶
func (e *DuplicateFieldError) Error() string
type DuplicateFieldPolicy ¶
type DuplicateFieldPolicy int
DuplicateFieldPolicy controls what happens when a custom Attr has the same key as a canonical field (e.g. loza.String("service", "x") when service is already set from Params).
type ErrorExtractor ¶
ErrorExtractor converts an error into an ErrorInfo. Override this on Config to customise extraction (e.g. for pkg/errors).
type ErrorInfo ¶
type ErrorInfo struct {
Type string `json:"type"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
Retriable bool `json:"retriable,omitempty"`
Stack string `json:"stack,omitempty"`
Cause string `json:"cause,omitempty"`
}
ErrorInfo is the structured representation of an error attached to an event.
func DefaultErrorExtractor ¶
DefaultErrorExtractor is the built-in extractor used when none is configured.
func DefaultErrorExtractorNoStack ¶
DefaultErrorExtractorNoStack is equivalent to DefaultErrorExtractor but omits stack traces.
type Event ¶
type Event struct {
// ── Correlation IDs ──────────────────────────────────────────────────────
Timestamp time.Time
SchemaVersion string
EventVersion string
EventID string
RequestID string
TraceID string
SpanID string
ParentID string
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 ExpectEvent ¶
func ExpectEvent(t testing.TB, store *MemorySinkStore) *Event
ExpectEvent asserts that store contains at least one event.
func FromContext ¶
FromContext retrieves the canonical Event from ctx. Returns (nil, false) if StartEvent has not been called.
func SanitizeEvent ¶
SanitizeEvent clones the event and applies the global config's redactor and security settings. The original event is never mutated.
func (*Event) Add ¶
Add appends a value to an array field on an active event. If the field doesn't exist, it creates a new array with the value. If the field exists but is not an array, it returns an error. Requirements: 2.4
func (*Event) AddCheckpoint ¶
func (e *Event) AddCheckpoint(cp EventCheckpoint) error
AddCheckpoint appends an EventCheckpoint under the mutex.
func (*Event) Checkpoint ¶
Checkpoint records a checkpoint on this event.
func (*Event) Delete ¶
Delete removes attrs by key. Dot keys can target group children (e.g. "user.id").
func (*Event) FinishError ¶
FinishError marks this event as failed.
func (*Event) IsFinished ¶
IsFinished reports if event finish timestamp is set.
func (*Event) MarkEmitted ¶
MarkEmitted is kept for compatibility with older tests and helper code. New emit paths should use beginEmit/markEmitted so validation failures do not burn the emitted state.
func (*Event) MuLock ¶
func (e *Event) MuLock()
MuLock acquires the event mutex. Use sparingly; prefer the accessor methods.
func (*Event) Set ¶
Set upserts attrs by key and applies canonical fields when keys match. Requirements: 1.3, 2.3
func (*Event) SetOutcome ¶
SetOutcome sets the Outcome field.
func (*Event) 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) 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
type EventAlreadyFinishedError ¶
type EventAlreadyFinishedError struct {
EventID string
}
EventAlreadyFinishedError is returned when Finish or FinishError is called more than once before emit.
func (*EventAlreadyFinishedError) Error ¶
func (e *EventAlreadyFinishedError) Error() string
type EventBuffer ¶
type EventBuffer struct {
// contains filtered or unexported fields
}
EventBuffer is an in-memory buffer for events with automatic flushing. It implements batching and buffering per Requirement 33.
Requirements: 33.1, 33.2, 33.3, 33.4, 33.5, 33.6, 33.7, 33.8, 33.9, 33.10, 33.11
func NewEventBuffer ¶
func NewEventBuffer(cfg EventBufferConfig) *EventBuffer
NewEventBuffer creates a new event buffer with the given configuration. Requirement 33.1
func (*EventBuffer) Add ¶
Add adds an event to the buffer. If the buffer reaches batch_size, it flushes automatically. If the buffer exceeds max_buffer_size, oldest events are dropped. Requirements: 33.4, 33.8, 33.9
func (*EventBuffer) Close ¶
func (b *EventBuffer) Close(ctx context.Context) error
Close stops the buffer and flushes remaining events. Requirement 33.7: flush on Shutdown()
func (*EventBuffer) DroppedCount ¶
func (b *EventBuffer) DroppedCount() int64
DroppedCount returns the total number of events dropped due to buffer overflow. Requirement 33.9: increment events_dropped_total
func (*EventBuffer) Flush ¶
func (b *EventBuffer) Flush(ctx context.Context) error
Flush immediately flushes all buffered events. Requirement 33.6
func (*EventBuffer) Size ¶
func (b *EventBuffer) Size() int
Size returns the current number of buffered events. Requirement 33.10: expose buffer_size gauge
type EventBufferConfig ¶
type EventBufferConfig struct {
// BatchSize is the number of events that trigger an automatic flush.
// Default: 100. Requirement 33.2
BatchSize int
// FlushInterval is the maximum time between flushes.
// Default: 5 seconds. Requirement 33.3
FlushInterval time.Duration
// MaxBufferSize is the maximum number of events to buffer.
// When exceeded, oldest events are dropped. Requirement 33.8
MaxBufferSize int
// FlushFunc is called to flush buffered events.
FlushFunc func(ctx context.Context, events []*Event, encoded [][]byte) error
}
EventBufferConfig configures the event buffer.
type EventCheckpoint ¶
type EventCheckpoint struct {
// Name is a dot-separated event name, e.g. "payment.started".
Name string
// AtMS is milliseconds elapsed from Event.StartedAt to when this was recorded.
AtMS int64
// Attrs holds optional key-value context for this checkpoint.
Attrs []Attr
}
EventCheckpoint is a named breadcrumb recorded inside a canonical event. Checkpoints are lightweight — they store a name, elapsed milliseconds, and optional attrs. They appear in the final emitted JSON under "checkpoints".
type EventClosedError ¶
type EventClosedError struct {
EventID string
State EventState
}
EventClosedError is returned when code attempts to mutate or finish an event after the lifecycle has moved past the mutable states.
func (*EventClosedError) Error ¶
func (e *EventClosedError) Error() string
type EventFunc ¶
EventFunc runs application work while the canonical event is active. Return a non-nil error to mark the event as failed.
type 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 ¶
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 ¶
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 ¶
HTTPResponse represents the response from an HTTP request.
type HTTPTransport ¶
type HTTPTransport struct {
// contains filtered or unexported fields
}
HTTPTransport provides HTTP client with retry logic for event delivery.
func NewHTTPTransport ¶
func NewHTTPTransport(cfg HTTPTransportConfig) *HTTPTransport
NewHTTPTransport creates a new HTTP transport with retry logic.
func (*HTTPTransport) Client ¶
func (t *HTTPTransport) Client() *http.Client
Client returns the underlying HTTP client.
func (*HTTPTransport) Do ¶
func (t *HTTPTransport) Do(ctx context.Context, req *http.Request) (*HTTPResponse, error)
Do executes an HTTP request with retry logic. It implements exponential backoff with jitter and honors Retry-After headers.
type HTTPTransportConfig ¶
type HTTPTransportConfig struct {
MaxRetries int
MaxBackoff time.Duration
Timeout time.Duration
ConnectionTimeout time.Duration
Client *http.Client
Metrics *MetricsCollector
}
HTTPTransportConfig configures the HTTP transport.
type IDGenerator ¶
type IDGenerator interface {
NewID() string
}
IDGenerator generates unique string IDs for events.
type JSONEventEncoder ¶
type JSONEventEncoder struct {
Pretty bool
ExpandDotKeys bool
TimeFormat TimeFormat
}
JSONEventEncoder is the default Encoder producing compact or pretty NDJSON.
func JSONEncoder ¶
func JSONEncoder() *JSONEventEncoder
JSONEncoder returns the default compact JSON encoder.
func PrettyJSONEncoder ¶
func PrettyJSONEncoder() *JSONEventEncoder
PrettyJSONEncoder returns a pretty-print JSON encoder.
func (*JSONEventEncoder) EncodeEvent ¶
func (e *JSONEventEncoder) EncodeEvent(dst []byte, ev *Event) ([]byte, error)
EncodeEvent encodes ev into dst and returns the extended slice.
type Kind ¶
type Kind uint8
Kind identifies the type stored in an Attr's Value field. Using Kind avoids reflection on the hot encoding path.
const ( KindString Kind = iota KindInt // stored as int KindInt64 // stored as int64 KindUint64 // stored as uint64 KindFloat64 // stored as float64 KindBool // stored as bool KindTime // stored as time.Time KindDuration // stored as time.Duration KindGroup // stored as []Attr KindAny // stored as any — slow path via encoding/json KindStringer // stored as fmt.Stringer KindError // stored as error KindNull // stored as nil )
type 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 Level ¶
type Level uint8
Level represents the severity level of a log event.
func ParseLevel ¶
ParseLevel parses a string into a Level. Defaults to LevelInfo on unknown input.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is an instance of the LOZA-Go logging pipeline.
func NewClient ¶
NewClient creates a new Logger applying the full configuration precedence: code initialization > environment variables > configuration file > defaults.
This implements Requirement 32.1, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9.
The cfg parameter represents code-level configuration (highest precedence). Environment variables are loaded automatically. A loza.yaml file is loaded from the current directory if present.
func (*Logger) Alias ¶
Alias creates an immutable child logger that preserves config and emits loza.alias.
func (*Logger) Breadcrumb ¶
Breadcrumb logs a breadcrumb at debug level for tracing user flows.
func (*Logger) Checkpoint ¶
Checkpoint records a named breadcrumb inside the event.
func (*Logger) Child ¶
func (l *Logger) Child(options ...ConfigOption) (*Logger, error)
Child creates a nested logger with config overrides applied.
func (*Logger) CloneEvent ¶
CloneEvent clones the event in ctx and returns a standalone copy.
func (*Logger) CurrentEvent ¶
CurrentEvent returns the active event from ctx.
func (*Logger) DebugContext ¶
DebugContext emits an immediate debug log line with explicit context and event name.
func (*Logger) Emit ¶
Emit encodes and delivers the canonical event in ctx to all sinks. Idempotent — safe to call via defer and also explicitly.
func (*Logger) EmitEventWithContext ¶
EmitEventWithContext encodes and delivers ev with the given context.
func (*Logger) EnrichGroup ¶
EnrichGroup appends attrs as a named group to the event in ctx.
func (*Logger) ErrorContext ¶
func (l *Logger) ErrorContext(ctx context.Context, msg string, err error, event string, attrs ...Attr)
ErrorContext emits an immediate error log line with explicit context and event name.
func (*Logger) 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) FinishError ¶
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) InfoContext ¶
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) NoticeContext ¶
NoticeContext emits an immediate notice log line with explicit context and event name.
func (*Logger) PanicRecoveryEnabled ¶
PanicRecoveryEnabled reports whether runtime wrappers should recover panics.
func (*Logger) StartEvent ¶
StartEvent begins a canonical wide event, stores it in ctx, and returns the new ctx. Requirements: 39.1, 39.2, 39.3, 39.4, 39.5, 39.6, 39.7, 39.8
func (*Logger) StartGroup ¶
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 ¶
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) WarnContext ¶
WarnContext emits an immediate warn log line with explicit context and event name.
type MemorySinkStore ¶
type MemorySinkStore struct {
// contains filtered or unexported fields
}
func (*MemorySinkStore) Clear ¶
func (m *MemorySinkStore) Clear()
func (*MemorySinkStore) Events ¶
func (m *MemorySinkStore) Events() []*Event
func (*MemorySinkStore) Len ¶
func (m *MemorySinkStore) Len() int
func (*MemorySinkStore) Raw ¶
func (m *MemorySinkStore) Raw() [][]byte
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector implements Prometheus metrics for the SDK. Requirements: 49.1, 49.2, 49.3, 49.4, 49.5, 49.6, 49.7, 49.8, 49.9, 49.10
func NewMetricsCollector ¶
func NewMetricsCollector(namespace string, maxBufferSize int) *MetricsCollector
NewMetricsCollector creates a new Prometheus metrics collector for the SDK. Requirements: 49.10
func (*MetricsCollector) Handler ¶
func (mc *MetricsCollector) Handler() http.Handler
Handler returns an HTTP handler for Prometheus metrics endpoint. Requirement: 49.10
func (*MetricsCollector) ObserveEmitDuration ¶
func (mc *MetricsCollector) ObserveEmitDuration(duration time.Duration)
ObserveEmitDuration records the duration of an Emit operation. Requirement: 49.5
func (*MetricsCollector) OnBackpressure ¶
func (mc *MetricsCollector) OnBackpressure()
OnBackpressure increments the backpressure_total counter. Requirement: 49.9
func (*MetricsCollector) OnEventCreated ¶
func (mc *MetricsCollector) OnEventCreated()
OnEventCreated increments the events_created_total counter. Requirement: 49.1
func (*MetricsCollector) OnEventDropped ¶
func (mc *MetricsCollector) OnEventDropped(reason string)
OnEventDropped increments the events_dropped_total counter with reason label. Requirement: 49.4
func (*MetricsCollector) OnEventEmitted ¶
func (mc *MetricsCollector) OnEventEmitted(success bool)
OnEventEmitted increments the events_emitted_total counter with status label. Requirement: 49.3
func (*MetricsCollector) OnEventFinished ¶
func (mc *MetricsCollector) OnEventFinished()
OnEventFinished increments the events_finished_total counter. Requirement: 49.2
func (*MetricsCollector) OnRetry ¶
func (mc *MetricsCollector) OnRetry(attempt int)
OnRetry increments the retry_total counter with attempt label. Requirement: 49.8
func (*MetricsCollector) Registry ¶
func (mc *MetricsCollector) Registry() *prometheus.Registry
Registry returns the Prometheus registry for custom registration. Requirement: 49.11
func (*MetricsCollector) SetBufferSize ¶
func (mc *MetricsCollector) SetBufferSize(size int)
SetBufferSize sets the current buffer size directly. Requirement: 49.6
type 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
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.
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.
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 ¶
func (h *PrometheusStatsHandler) Metrics() *MetricsCollector
Metrics returns the underlying MetricsCollector for direct access.
func (*PrometheusStatsHandler) ObserveEmitDuration ¶
func (h *PrometheusStatsHandler) ObserveEmitDuration(d time.Duration)
ObserveEmitDuration records the duration of an emit operation.
func (*PrometheusStatsHandler) OnDeliveryFailed ¶
func (h *PrometheusStatsHandler) OnDeliveryFailed(_ *Event, _ error)
OnDeliveryFailed records an explicit delivery failure without counting it as a success emit.
func (*PrometheusStatsHandler) OnDrop ¶
func (h *PrometheusStatsHandler) OnDrop(reason string)
OnDrop is called when an event is dropped. Requirement: 34.4
func (*PrometheusStatsHandler) OnEmit ¶
func (h *PrometheusStatsHandler) OnEmit(ev *Event)
OnEmit is called when an event is successfully emitted. Requirement: 34.3
func (*PrometheusStatsHandler) OnError ¶
func (h *PrometheusStatsHandler) OnError(err error)
OnError is called when an error occurs during asynchronous operations. Requirement: 34.3, 34.4
func (*PrometheusStatsHandler) OnEventCreated ¶
func (h *PrometheusStatsHandler) OnEventCreated()
OnEventCreated increments the events_created_total counter.
func (*PrometheusStatsHandler) OnEventFinished ¶
func (h *PrometheusStatsHandler) OnEventFinished()
OnEventFinished increments the events_finished_total counter.
type 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
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 ¶
ComposeRedactors combines multiple redactors; the first match wins.
func DefaultRedactor ¶
func DefaultRedactor() Redactor
DefaultRedactor returns a Redactor that replaces common sensitive keys.
func RedactKeys ¶
RedactKeys returns a Redactor that replaces values for the given keys.
func RedactPatterns ¶
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 ¶
RotatingFileConfig configures the rotating file sink.
type Sampler ¶
Sampler decides whether an event should be emitted.
func AllSampler ¶
AllSampler keeps an event only if all samplers keep it.
func AllowFields ¶
AllowFields returns a Sampler that keeps events when the attr list contains any of the specified keys.
func AnySampler ¶
AnySampler keeps an event if any sampler keeps it.
func BlockFields ¶
BlockFields returns a Sampler that drops events when the attr list contains any of the specified keys.
func SampleByEvent ¶
SampleByEvent keeps events whose event name matches one of names.
func SampleByHeader ¶
SampleByHeader keeps events where a header attr equals value. It checks keys:
- http.header.<name>
- http.headers.<name>
- <name>
where <name> is lower-cased with "_" converted to "-".
func SampleByOutcome ¶
SampleByOutcome keeps events whose outcome matches one of outcomes.
func SampleFeatureFlag ¶
SampleFeatureFlag keeps events where feature/feature_flags.<name> matches value.
func SampleRandom ¶
SampleRandom keeps approximately rate of events (0..1).
func SampleRateLimited ¶
SampleRateLimited keeps at most rate events per window using a token-bucket strategy.
func SampleRoutes ¶
SampleRoutes keeps events whose route or path matches one of routes.
func SampleSlowRequests ¶
SampleSlowRequests keeps events with duration >= threshold. threshold may be time.Duration, int64 (milliseconds), or int (milliseconds).
func SampleStatusCodes ¶
SampleStatusCodes keeps events whose status code matches one of codes.
func SampleTenants ¶
SampleTenants keeps events whose tenant identifier matches one of ids. It checks both "tenant.id" and "tenant_id".
func SampleUsers ¶
SampleUsers keeps events whose user identifier matches one of ids. It checks both "user.id" and "user_id".
type Schema ¶
Schema controls final output shape for emitted events.
func CustomSchema ¶
CustomSchema creates a schema from a projection function.
func FlatSchema ¶
func FlatSchema() Schema
FlatSchema emits flattened attrs for analytics databases.
func NestedSchema ¶
func NestedSchema() Schema
NestedSchema emits canonical fields with nested attrs/groups.
func OTelLogSchema ¶
func OTelLogSchema() Schema
OTelLogSchema emits an OpenTelemetry-flavored log shape.
type SchemaFunc ¶
SchemaFunc allows mapping an EventView to an output object.
type SecurityConfig ¶
type SecurityConfig struct {
RedactByDefault bool
AllowPII bool
MaxFieldBytes int
MaxEventBytes int
MaxAttrCount int
DropOversizedEvents bool
}
SecurityConfig controls event-size and sensitive-data limits.
type Sink ¶
type Sink interface {
// Name returns a human-readable identifier for this sink.
Name() string
// WriteEvent delivers an already-encoded event to the sink.
// encoded is the JSON bytes (including trailing newline).
// ev is the original Event for sinks that need typed field access.
WriteEvent(ctx context.Context, encoded []byte, ev *Event) error
// Flush forces any buffered data to be written.
Flush(ctx context.Context) error
// Close releases resources held by the sink.
Close(ctx context.Context) error
}
Sink receives encoded events and delivers them to a destination. All methods must be safe for concurrent use.
func CollectorSink ¶
func CollectorSink(cfg CollectorSinkConfig) (Sink, error)
func HTTPBatchSink ¶
func HTTPBatchSink(cfg HTTPBatchSinkConfig) (Sink, error)
func LegacyHTTPBatchSink ¶
LegacyHTTPBatchSink is a convenience wrapper that creates a CollectorSink. Deprecated: Use HTTPBatchSink with HTTPBatchSinkConfig for real batching.
func OTLSink ¶
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.
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 StackError ¶
type StackError interface {
StackTrace() string
}
StackError is implemented by errors that carry a stack trace string.
type StatsHandler ¶
StatsHandler receives logger pipeline telemetry callbacks.
type StopwatchHandle ¶
type StopwatchHandle struct {
// contains filtered or unexported fields
}
StopwatchHandle is a standalone timer that measures elapsed time without an event reference.
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 ¶
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.
Source Files
¶
- attr.go
- buffer.go
- builder.go
- canonical.go
- checkpoint.go
- clock.go
- collector_client.go
- config.go
- config_file.go
- config_options.go
- context.go
- core.go
- dotkey.go
- duplicate.go
- duplicate_policy.go
- encoder.go
- errors.go
- event.go
- event_api.go
- event_builder.go
- http_client.go
- http_context.go
- http_transport.go
- level.go
- logger.go
- lql.go
- metrics.go
- params.go
- pipeline.go
- redactor.go
- run.go
- sampler.go
- sanitize.go
- schema.go
- security.go
- sink.go
- spec_contract.go
- standard_sinks.go
- structure.go
- testing_helpers.go
- timing.go
- trace_context.go
- uuidv7.go
- version.go