duckbug

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 5 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

duckbug-go

Go SDK for DuckBug errors, logs, and transactions.

This module follows the DuckBug SDK architecture from duckbug-sdk-spec, while using the real ingest contract from duckbug/backend:

  • POST /ingest/{projectID}:{key}/errors
  • POST /ingest/{projectID}:{key}/errors/batch
  • POST /ingest/{projectID}:{key}/logs
  • POST /ingest/{projectID}:{key}/logs/batch
  • POST /ingest/{projectID}:{key}/transactions

Compatibility

  • Go 1.26.10+. The go directive in go.mod is the source of truth. The HTTP/2 security fixes in golang.org/x/net require Go 1.26; the minimum uses the current patched 1.26 release. Upgrading from SDK 0.4 also requires upgrading consumers still using Go 1.25.
  • Every change is validated on that minimum and on the current Go release. The exact versions are the matrix in the CI workflow under .github/workflows/, and are not repeated here.
  • Releases are expected to be published via git tags in the v* format.

Install

go get github.com/duckbugio/duckbug-go

To install a tagged release:

go get github.com/duckbugio/duckbug-go@v0.3.1

Quick start

package main

import (
    "context"
    "log"
    "os"
    "strings"

    duckbug "github.com/duckbugio/duckbug-go"
)

func main() {
    dsn := strings.TrimSpace(os.Getenv("DUCKBUG_DSN"))
    if dsn == "" {
        log.Fatal("DUCKBUG_DSN is required")
    }

    duck := duckbug.New(
        dsn,
        duckbug.WithService("checkout"),
        duckbug.WithEnvironment("production"),
    )
    defer duck.Flush(context.Background())

    duck.Log("warning", "payment provider timeout", map[string]any{
        "provider": "stripe",
    })

    if err := doWork(); err != nil {
        duck.Quack(err)
    }
}

This is the smallest useful setup: the SDK only needs a DSN. Environment variable naming is up to your application; DUCKBUG_DSN is just the simplest convention for examples.

If you want richer context, you can optionally pass duckbug.WithService(...), duckbug.WithEnvironment(...), duckbug.WithRelease(...), duckbug.WithServerName(...), custom provider options, or a custom pond.Pond.

HTTP + logging example
package main

import (
    "context"
    "log/slog"
    "net/http"

    duckbug "github.com/duckbugio/duckbug-go"
    duckbughttp "github.com/duckbugio/duckbug-go/integrations/nethttp"
    duckbugslog "github.com/duckbugio/duckbug-go/integrations/slog"
)

func main() {
    duck := duckbug.New(
        "https://duckbug.io/api/ingest/<projectID>:<publicKey>",
        duckbug.WithSensitiveFields("password", "token"),
        duckbug.WithEnvironment("production"),
        duckbug.WithRelease("checkout@1.2.3"),
        duckbug.WithService("checkout"),
    )

    logger := slog.New(duckbugslog.NewHandler(duck, slog.Default().Handler()))
    logger.Warn("checkout degraded", "provider", "stripe")

    handler := duckbughttp.Middleware(
        duck,
        duckbughttp.WithProductionDefaults(),
    )(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusNoContent)
    }))

    _ = handler

    duck.Flush(context.Background())
}
HTTP response observation

The middleware records the first final HTTP status. Informational responses can precede it; status 101 is terminal. Writes and supported flush operations establish an implicit 200. Streaming and string writes follow the same accounting, and the wrapper preserves the underlying optional writer interfaces. Put this middleware outside other response-writer middleware, so controller operations from inner handlers reach its hooks. An outer writer that exposes controller capabilities only through Unwrap can let http.ResponseController bypass observation; that ordering is unsupported and can produce an incorrect recorded status. An outer writer is compatible only when it directly delegates those capabilities. Verify the writer order when adopting the middleware in an existing server stack.

Handled-failure snippets contain only bytes accepted by the underlying writer. responseAcceptedBytes counts those bytes; buffering and HEAD responses mean this does not prove delivery to the client. Use WithHandled5xxMaxBodyBytes(0) to omit response snippets while retaining failure status and accepted-byte count.

A panic after a committed response retains that status and does not append a fallback body. With WithRepanic(true), an uncommitted panic is rethrown for outer recovery; its future HTTP status is unknown, so the transaction omits the status measurement. A hijacked connection without an observed status has the same unknown-status boundary. An ordinary empty handler defaults to 200 on return.

Branded surface

  • Duck is the main runtime facade.
  • New(dsn, ...) is the shortest setup path for the first-party provider.
  • Quack(err) is the branded manual error capture API.
  • pond.Ripple(...) builds the context/sanitization subsystem.
  • Log(...) is the canonical log capture API.
  • StartTransaction(...) and CaptureTransaction(...) provide the performance/trace ingest surface.

Privacy defaults

  • Sensitive nested fields are masked with ***.
  • Sensitive header names are masked with ***.
  • Query/body/session/cookies/files/env are attached in the canonical event model and can be disabled in the DuckBug provider privacy options.
  • env capture is disabled by default in the first-party provider.
  • net/http middleware does not read request bodies unless you explicitly enable WithReadBody(true).

Runtime defaults

  • The first-party provider uses a background queue by default, so Log, Quack, CaptureTransaction and slog bridge calls do not block the hot path on network I/O.
  • The default transport is tuned for application safety: short connection timeout and no retry storm on the request path.
  • Delivery is retried on transport errors, 408, 429 and every 5xx, including status codes this SDK has never been taught about - those are what an edge in front of the installation invents, and dropping the event on the first one would lose it silently. 501 Not Implemented is the single exception and is final, because it means the capability is not configured in that DuckBug installation and repeating the request cannot change that. Everything else is decided after one attempt. 409 Conflict is not a failure: it means the backend already holds this eventId, so the result is marked Duplicate, TransportResult.IsSuccess() reports true and the transport failure handler is not called. Every other 4xx is reported to the transport failure handler after one attempt.
  • The retry predicate is identical in duckbug-go, duckbug-js and duckbug-php. What a duplicate looks like afterwards is not: duckbug-js also treats 409 as success, while duckbug-php hands it to its failure handler because its isSuccess() requires 2xx. All three agree on not retrying it.
  • Retries are opt-in here: WithMaxRetries defaults to 0, because this transport can run inline in the caller's request path. duckbug-js and duckbug-php default to 2.
  • Flush(...) waits for the provider queue and sends any buffered log/error batches, so it should be called on graceful shutdown.

slog integration

logger := slog.New(duckbugslog.NewHandler(duck, slog.Default().Handler()))
logger.Info("checkout started", "requestId", "req-123")

By default the SDK captures WARN+ from slog. To lower the threshold:

logger := slog.New(
    duckbugslog.NewHandler(
        duck,
        slog.Default().Handler(),
        duckbugslog.WithMinLevel(slog.LevelInfo),
    ),
)

zap integration

import (
    "os"

    duckbugzap "github.com/duckbugio/duckbug-go/integrations/zap"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

observerCore := zapcore.NewCore(
    zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
    zapcore.AddSync(os.Stdout),
    zapcore.InfoLevel,
)
logger := zap.New(duckbugzap.NewCore(duck, observerCore)).With(zap.String("service", "api"))
logger.Warn("checkout degraded", zap.String("provider", "stripe"))

zerolog integration

import (
    "os"

    duckbugzerolog "github.com/duckbugio/duckbug-go/integrations/zerolog"
    "github.com/rs/zerolog"
)

logger := zerolog.New(duckbugzerolog.NewWriter(duck, os.Stdout)).
    With().
    Timestamp().
    Str("service", "api").
    Logger()
logger.Warn().Str("provider", "stripe").Msg("checkout degraded")

net/http integration

handler := duckbughttp.Middleware(
    duck,
    duckbughttp.WithCaptureTransactions(true),
    duckbughttp.WithTransactionSampleRate(0.10),
)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    duck.LogContext(r.Context(), "info", "request received", map[string]any{
        "path": r.URL.Path,
    })
    w.WriteHeader(http.StatusNoContent)
}))

Provider options

The first-party DuckBug provider supports:

  • async non-blocking enqueue with bounded in-memory queue
  • batching with explicit Flush(...) and periodic background flush
  • single-shot transactions ingest
  • safe-by-default transport timeouts and configurable retry/backoff
  • beforeSend mutation/drop hook
  • transport failure hook
  • privacy controls for request sections and env

Transactions

Transactions mirror the current DuckBug backend and PHP SDK shape:

  • required payload fields: traceId, spanId, transaction, op, startTime, endTime, duration
  • optional fields: eventId, parentSpanId, status, context, measurements, spans, release, environment, dist, platform, serverName, service, requestId, user, sdk, runtime, extra
  • duplicate transaction ingest is treated as idempotent success by the backend

Example:

tx := duck.StartTransaction("GET /checkout", "http.server")

span := tx.StartChild("db.query", "select order")
span.SetData(map[string]any{
    "sql": "select * from orders where id = ?",
})
span.Finish("ok")

tx.AddMeasurement("db.rows", 1, "")
tx.Finish("ok")

duck.CaptureTransaction(tx)

Current status

Implemented in this iteration:

  • core runtime for errors, logs, and transactions
  • branded Duck / Quack / pond.Ripple
  • first-party DuckBug provider
  • slog, zap, and zerolog bridges
  • net/http middleware compatible with chi
  • schema copies and tests against the current payload contract for errors and logs
  • transaction payload tests aligned with duckbug/backend and duckbug-php

Release process

  • Push a semver-style tag like v0.2.0.
  • The release workflow re-runs module checks and creates a GitHub Release.
  • Consumers install the module through the standard Go module mechanism via go get.

Documentation

Index

Constants

View Source
const (
	EventTypeError       = corepkg.EventTypeError
	EventTypeLog         = corepkg.EventTypeLog
	EventTypeTransaction = corepkg.EventTypeTransaction

	LevelDebug = corepkg.LevelDebug
	LevelInfo  = corepkg.LevelInfo
	LevelWarn  = corepkg.LevelWarn
	LevelError = corepkg.LevelError
	LevelFatal = corepkg.LevelFatal
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchItemResult

type BatchItemResult = corepkg.BatchItemResult

type Config

type Config = corepkg.Config

type Duck

type Duck = corepkg.Duck

func New added in v0.2.2

func New(dsn string, options ...Option) *Duck

New creates a Duck runtime with the first-party DuckBug provider already wired. It is the shortest path for the common "one DSN + optional metadata" setup.

func NewDuck

func NewDuck(config Config) *Duck

type DuckBugBeforeSendFunc

type DuckBugBeforeSendFunc = duckbugprovider.BeforeSendFunc

type DuckBugHTTPTransport

type DuckBugHTTPTransport = duckbugprovider.HTTPTransport

func NewDuckBugHTTPTransport

func NewDuckBugHTTPTransport(config DuckBugHTTPTransportConfig) *DuckBugHTTPTransport

type DuckBugHTTPTransportConfig

type DuckBugHTTPTransportConfig = duckbugprovider.HTTPTransportConfig

type DuckBugPrivacyOptions

type DuckBugPrivacyOptions = duckbugprovider.PrivacyOptions

func DefaultDuckBugPrivacyOptions

func DefaultDuckBugPrivacyOptions() DuckBugPrivacyOptions

type DuckBugProvider

type DuckBugProvider = duckbugprovider.Provider

func NewDuckBugProvider

func NewDuckBugProvider(dsn string, options ...DuckBugProviderOption) *DuckBugProvider

func NewDuckBugProviderWithConfig

func NewDuckBugProviderWithConfig(config DuckBugProviderConfig) *DuckBugProvider

type DuckBugProviderConfig

type DuckBugProviderConfig = duckbugprovider.Config

type DuckBugProviderOption

type DuckBugProviderOption = duckbugprovider.Option

func WithAsync added in v0.2.2

func WithAsync(enabled bool) DuckBugProviderOption

func WithBatchSize added in v0.2.2

func WithBatchSize(size int) DuckBugProviderOption

func WithBeforeSend added in v0.2.2

func WithConnectionTimeout added in v0.2.2

func WithConnectionTimeout(timeout time.Duration) DuckBugProviderOption

func WithFlushInterval added in v0.2.2

func WithFlushInterval(interval time.Duration) DuckBugProviderOption

func WithMaxRetries added in v0.2.2

func WithMaxRetries(maxRetries int) DuckBugProviderOption

func WithPrivacy added in v0.2.2

func WithPrivacy(options DuckBugPrivacyOptions) DuckBugProviderOption

func WithQueueSize added in v0.2.2

func WithQueueSize(size int) DuckBugProviderOption

func WithRetryDelay added in v0.2.2

func WithRetryDelay(delay time.Duration) DuckBugProviderOption

func WithTimeout added in v0.2.2

func WithTimeout(timeout time.Duration) DuckBugProviderOption

func WithTransport added in v0.2.2

func WithTransport(transport DuckBugTransport) DuckBugProviderOption

func WithTransportFailureHandler added in v0.2.2

func WithTransportFailureHandler(fn func(FailureInfo)) DuckBugProviderOption

type DuckBugTransport

type DuckBugTransport = duckbugprovider.Transport

type Event

type Event = corepkg.Event

type EventType

type EventType = corepkg.EventType

type FailureInfo

type FailureInfo = corepkg.FailureInfo

type FlushableProvider

type FlushableProvider = corepkg.FlushableProvider

type Level

type Level = corepkg.Level

func NormalizeLevel

func NormalizeLevel(level any) Level

type Option added in v0.2.2

type Option func(*runtimeConfig)

func WithEnvironment added in v0.2.2

func WithEnvironment(environment string) Option

func WithPond added in v0.2.2

func WithPond(p *pond.Pond) Option

func WithProviderOptions added in v0.2.2

func WithProviderOptions(options ...DuckBugProviderOption) Option

func WithRelease added in v0.2.2

func WithRelease(release string) Option

func WithSensitiveFields added in v0.2.2

func WithSensitiveFields(fields ...string) Option

func WithServerName added in v0.2.2

func WithServerName(serverName string) Option

func WithService added in v0.2.2

func WithService(service string) Option

type Provider

type Provider = corepkg.Provider

type Span

type Span = corepkg.Span

type Transaction

type Transaction = corepkg.Transaction

type TransportResult

type TransportResult = corepkg.TransportResult

Directories

Path Synopsis
examples
basic command
integrations
zap
internal
providers

Jump to

Keyboard shortcuts

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