pingwright

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 32 Imported by: ? modules, 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

pingwright-go

The official Go library for Pingwright. It sends your service's logs, metrics and errors to Pingwright with one call, using standard OpenTelemetry (OTLP/HTTP) under the hood.

  • Logs: a log/slog logger that writes locally and to Pingwright, with trace and span ids attached.
  • Errors: CaptureError and Recover turn errors and panics into issues, grouped by type and stack.
  • Metrics: Go runtime metrics, HTTP server metrics from Middleware, and your own through Meter.

Install

go get github.com/Pingwright-Labs/pingwright-go

Requires Go 1.26 or newer (the OpenTelemetry Go SDK it builds on requires it).

Quickstart

func main() {
	ctx := context.Background()
	shutdown, err := pingwright.Init(ctx, pingwright.Options{
		Key:         os.Getenv("PINGWRIGHT_KEY"), // pwi_..., from Settings → Telemetry
		Service:     "billing-api",
		Environment: "production",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { // flushes on exit, for at most 5 seconds
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = shutdown(ctx)
	}()
	defer pingwright.Recover(ctx) // reports a crash, then crashes as before

	slog.Info("started", "port", 8080) // stderr and Pingwright
}

Init makes pingwright.Logger() the slog default, so existing slog.Info(...) calls (and the standard log package) go to Pingwright without changes.

Init returns an error only for a configuration that cannot work (a key that is blank or contains whitespace, an endpoint that is not an http(s) URL). Everything else degrades instead of failing: no key means local mode, and an unreachable or rejecting endpoint means export errors in your local output.

It never gets in your way. The library does not panic in your code (Recover re-panics on purpose, and Middleware aborts a half-written response, see below), and it never blocks your code on the network: records are batched and exported in the background, and shutdown returns by the context's deadline, or after 5 seconds when the context has none.

net/http

mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
	slog.InfoContext(r.Context(), "loading order", "id", r.PathValue("id"))
	// ...
})
log.Fatal(http.ListenAndServe(":8080", pingwright.Middleware(mux)))

Middleware records OpenTelemetry HTTP server metrics (http.server.request.duration and friends, with http.route from the Go 1.22 mux pattern), reports a panic in a handler as an error and answers 500 instead of crashing, and picks up an incoming traceparent header so logs written with r.Context() carry the caller's trace id.

If the handler had already started the response when it panicked, a 500 is no longer possible. Middleware then reports the panic and panics with http.ErrAbortHandler, so net/http drops the connection and the client sees a broken response (as it would without Middleware) instead of a truncated body that looks complete.

Errors and panics

if err := charge(ctx, order); err != nil {
	pingwright.CaptureError(ctx, err, slog.String("order.id", order.ID))
	return err
}

CaptureError sends a log record at ERROR with the OpenTelemetry exception attributes:

Attribute Value
exception.type %T of the innermost error under plain wrappers (fmt.Errorf("…: %w"), errors.Join, *url.Error, pkg/errors), e.g. *net.OpError
exception.message err.Error() (the type, if Error() panics, as for a typed nil pointer)
exception.stacktrace the stack at the call site, in Go's runtime/debug.Stack format, your frame first

Pingwright groups these into issues by type and the top frames of your own code.

defer pingwright.Recover(ctx) at the top of main and of each goroutine reports a panic at FATAL, with the stack from the line that panicked, flushes it, and panics again, so the process still crashes the way it would have.

Configuration

Option Environment variable Default
Key (pwi_…) PINGWRIGHT_KEY none: local mode
Service (service.name) OTEL_SERVICE_NAME the executable's name
Environment (deployment.environment.name) OTEL_RESOURCE_ATTRIBUTES none
Version (service.version) OTEL_RESOURCE_ATTRIBUTES none
Endpoint PINGWRIGHT_ENDPOINT https://ingest.pingwright.app
ResourceAttributes OTEL_RESOURCE_ATTRIBUTES none
LogLevel (slog.Leveler: slog.LevelDebug, a *slog.LevelVar, …) slog.LevelInfo (local and sent)
Output / TextOutput JSON to os.Stderr
Handler (your own slog.Handler for local output; Output and TextOutput are then ignored) none

An option set in code wins over its environment variable. Surrounding whitespace in the key is trimmed. A key that doesn't start with pwi_ gets one local warning and is sent anyway; the server decides. A plain http:// endpoint to a host other than localhost gets one local warning, since the key would travel unencrypted.

Local mode. Without a key, Init prints one warning and sends nothing. Logging, CaptureError, Recover, Middleware and Meter all still work locally, so development and tests need no setup.

What is sent

  • Logs to POST /v1/logs (OTLP/HTTP protobuf, gzip, Authorization: Bearer pwi_…), batched, at LogLevel and above. Record attributes keep their names; trace and span ids come from the context.
  • Errors as log records at ERROR (CaptureError, Middleware) or FATAL (Recover) with the exception.* attributes above. They are sent even below LogLevel.
  • Metrics to POST /v1/metrics every 30 seconds: Go runtime metrics (go.memory.used, go.goroutine.count, …), HTTP server metrics from Middleware, and anything you record with pingwright.Meter or the global otel.Meter (Init sets the global MeterProvider).
  • Resource attributes: service.name, deployment.environment.name, service.version, host.name, the OpenTelemetry SDK version, and your own. For metrics, Pingwright keeps service.name, service.namespace, deployment.environment.name, k8s.cluster.name, k8s.namespace.name, k8s.deployment.name and cloud.region as labels and drops the rest (pod names and instance ids would multiply series on every deploy).
  • No traces. Pingwright does not store traces yet. Use your own tracer and exporter if you have one; its ids still end up on log records.

Exports time out after 10 seconds and are retried with backoff. While Init is active, the OpenTelemetry error handler writes export failures to your local output only (never back to Pingwright), at most once every 30 seconds per distinct error, with a count of the repeats it skipped. shutdown restores the previous handler.

Turning things off

pingwright.Options{
	DisableLogs:           true, // no log records (errors are still sent)
	DisableErrors:         true, // CaptureError/Recover send a plain error log; local output keeps the stack
	DisableMetrics:        true, // no metrics at all
	DisableRuntimeMetrics: true, // keep HTTP and custom metrics, skip Go runtime metrics
	KeepDefaultLogger:     true, // don't replace slog.Default
	Output:                io.Discard, // nothing written locally
}

Leave PINGWRIGHT_KEY unset to turn off sending entirely.

FAQ

Can I use plain OpenTelemetry instead? Yes. Pingwright's ingest is standard OTLP/HTTP, and this library is a convenience on top of the OpenTelemetry Go SDK. With your own otlploghttp and otlpmetrichttp exporters (plus the otelslog bridge for slog), set:

OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.pingwright.app
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer%20pwi_...
OTEL_SERVICE_NAME=billing-api
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production
OTEL_TRACES_EXPORTER=none

The same works from an OpenTelemetry Collector (otlphttp exporter with the authorization header). To get issues from plain OpenTelemetry, emit log records at ERROR or above with exception.type, exception.message and exception.stacktrace (Go panic or debug.Stack() format).

Does it slow my handlers down? No network call happens on the request path. Records are batched and exported in the background.

What happens on a crash? Recover flushes pending logs (up to 5 seconds) before re-panicking. For a normal exit, call the shutdown function from Init.

What if Pingwright is unreachable at shutdown? shutdown gives up at the context's deadline (5 seconds without one) and returns the error. Logs and metrics are flushed in parallel within that time.

Can I call Init twice? A second call returns ErrAlreadyInitialized. After shutdown, Init may be called again (useful in tests). Between the two, Logger() keeps writing to the local output you configured.

License

MIT

Documentation

Overview

Package pingwright sends a Go service's logs, metrics and errors to Pingwright (https://pingwright.app).

It is a thin layer over OpenTelemetry. Init configures an OTLP/HTTP log exporter and metric exporter that point at https://ingest.pingwright.app, and installs a log/slog logger that writes locally and to Pingwright at the same time. Errors are log records that carry the OpenTelemetry exception attributes (exception.type, exception.message, exception.stacktrace); Pingwright groups them into issues.

shutdown, err := pingwright.Init(ctx, pingwright.Options{
	Key:         os.Getenv("PINGWRIGHT_KEY"),
	Service:     "billing-api",
	Environment: "production",
})
if err != nil {
	log.Fatal(err)
}
defer func() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_ = shutdown(ctx)
}()

slog.Info("started") // goes to stderr and to Pingwright

Without a key (neither Options.Key nor PINGWRIGHT_KEY), Init prints one warning and runs in local mode: logging, CaptureError, Recover and Middleware keep working, and nothing is sent. This keeps development setups and tests free of configuration.

The library never panics in your code and never blocks it on the network: records are batched and exported in the background, export failures are written (rate-limited) to the local output only, and shutdown returns by the context's deadline, or after 5 seconds if the context has none.

Pingwright does not store traces, so none are exported. Trace and span ids from the context (set by your own tracer, or by Middleware from an incoming traceparent header) are attached to every log record.

Example
package main

import (
	"context"
	"log"
	"log/slog"
	"os"
	"time"

	"github.com/Pingwright-Labs/pingwright-go"
)

func main() {
	ctx := context.Background()
	shutdown, err := pingwright.Init(ctx, pingwright.Options{
		Key:         os.Getenv("PINGWRIGHT_KEY"),
		Service:     "billing-api",
		Environment: "production",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = shutdown(ctx)
	}()
	defer pingwright.Recover(ctx)

	slog.Info("started", "port", 8080)
}

Index

Examples

Constants

View Source
const DefaultEndpoint = "https://ingest.pingwright.app"

DefaultEndpoint is where telemetry goes unless Options.Endpoint or PINGWRIGHT_ENDPOINT says otherwise.

View Source
const LevelFatal = slog.LevelError + 4

LevelFatal is the level Recover uses for a panic that crashes the process. It is exported as OpenTelemetry severity FATAL (21).

View Source
const Version = "0.1.0"

Version is the version of this library, reported as the instrumentation scope version.

Variables

View Source
var ErrAlreadyInitialized = errors.New("pingwright: already initialized")

ErrAlreadyInitialized is returned by a second Init before the first one's shutdown function has run.

Functions

func CaptureError

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

CaptureError reports err to Pingwright as an error event: a log record at ERROR with exception.type, exception.message and exception.stacktrace. The stack trace starts at the caller of CaptureError. Pingwright groups events into issues by type and the top frames of your own code.

exception.type is the Go type (%T) of the innermost error under pure wrappers (fmt.Errorf %w, errors.Join, *url.Error, github.com/pkg/errors), so fmt.Errorf("fetch: %w", opErr) is reported as *net.OpError. exception.message is err.Error(), or the type when Error panics (as it does for a typed nil pointer). attrs are added to the record.

The trace and span ids in ctx, if any, are attached. A nil err does nothing. CaptureError never panics, also not on a nil ctx.

Example
package main

import (
	"context"
	"errors"
	"log/slog"

	"github.com/Pingwright-Labs/pingwright-go"
)

func main() {
	ctx := context.Background()
	if err := charge(ctx); err != nil {
		pingwright.CaptureError(ctx, err, slog.String("order.id", "o-123"))
	}
}

func charge(context.Context) error { return errors.New("card declined") }

func Init

func Init(ctx context.Context, opts Options) (shutdown func(context.Context) error, err error)

Init configures logs, metrics and errors for the process and returns a function that flushes and stops them. Call it once at startup and defer the returned function with a context that has a deadline (without one, it gives up after 5 seconds); it is safe to call more than once.

A second Init before shutdown returns ErrAlreadyInitialized. After shutdown, Init may be called again. The returned shutdown function is never nil, even when err is not.

Init sets the global OpenTelemetry MeterProvider, so libraries that use otel.Meter report through Pingwright too. It does not touch the global TracerProvider or propagator.

func Logger

func Logger() *slog.Logger

Logger returns the slog logger that writes locally and to Pingwright.

It is safe to call before Init, for example in a package-level variable: records go to stderr until Init runs and to the configured outputs after. Records get trace_id and span_id when their context carries a span, so use the Context variants (InfoContext, ErrorContext, ...) in request code.

Unless Options.KeepDefaultLogger is set, Init also makes this logger slog.Default, so plain slog.Info calls behave the same.

func Meter

func Meter(name string, opts ...metric.MeterOption) metric.Meter

Meter returns a meter from Pingwright's MeterProvider. Before Init, or with metrics off, it returns the global otel meter, which binds to Pingwright's provider once Init runs.

Example
package main

import (
	"context"

	"github.com/Pingwright-Labs/pingwright-go"
)

func main() {
	ctx := context.Background()
	jobs, _ := pingwright.Meter("worker").Int64Counter("jobs.processed")
	jobs.Add(ctx, 1)
}

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware instruments an HTTP server:

  • OpenTelemetry HTTP server metrics (http.server.request.duration and friends), with http.route taken from r.Pattern when next is an http.ServeMux (Go 1.22 patterns) or sits under one.
  • A panic in next is reported as an error event (ERROR, with the stack from the panicking frame and the request's method, path and route). If nothing was written yet, the client gets a 500 and the panic stops there. If the response was already started, Middleware panics with http.ErrAbortHandler so net/http aborts the connection and the client sees a broken response rather than a truncated one that looks complete. http.ErrAbortHandler from next passes through unreported.
  • An incoming W3C traceparent header is extracted (unless you set a global propagator yourself, which is then used), so logs written with r.Context() carry the caller's trace and span ids.

Wrap the whole mux so every route is covered:

http.ListenAndServe(":8080", pingwright.Middleware(mux))
Example
package main

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

	"github.com/Pingwright-Labs/pingwright-go"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
		slog.InfoContext(r.Context(), "loading order", "id", r.PathValue("id"))
	})
	log.Fatal(http.ListenAndServe(":8080", pingwright.Middleware(mux)))
}

func Recover

func Recover(ctx context.Context)

Recover reports a panic as an error event at FATAL, flushes it, and panics again with the same value, so the process still crashes as it would have. Use it as the first deferred call of main and of goroutines:

go func() {
	defer pingwright.Recover(ctx)
	work()
}()

The stack trace starts at the frame that panicked. Recover must be called directly by defer (not from inside another deferred function), as with the built-in recover. http.ErrAbortHandler is re-panicked without a report.

Example
package main

import (
	"context"

	"github.com/Pingwright-Labs/pingwright-go"
)

func main() {
	ctx := context.Background()
	go func() {
		defer pingwright.Recover(ctx)
		processQueue(ctx)
	}()
}

func processQueue(context.Context) {}

Types

type Options

type Options struct {
	// Key is the ingest key, starting with "pwi_". Falls back to
	// PINGWRIGHT_KEY. With neither, Init runs in local mode. Surrounding
	// whitespace is trimmed; a key that is blank or contains whitespace or
	// control characters makes Init fail. A key of any other unexpected
	// shape gets one local warning, and the server decides.
	Key string

	// Service is service.name. Falls back to OTEL_SERVICE_NAME, then to the
	// executable's name.
	Service string

	// Environment is deployment.environment.name, for example "production".
	Environment string

	// Version is service.version. Optional.
	Version string

	// Endpoint is the ingest base URL. Falls back to PINGWRIGHT_ENDPOINT,
	// then to DefaultEndpoint. "/v1/logs" and "/v1/metrics" are appended.
	Endpoint string

	// DisableLogs stops sending log records. Errors are still sent unless
	// DisableErrors is also set.
	DisableLogs bool

	// DisableErrors stops CaptureError, Recover and Middleware from sending
	// exception records. They still log locally, with the stack (and, with
	// logs on, send a plain error log without exception attributes, so no
	// issue is made).
	DisableErrors bool

	// DisableMetrics stops all metrics, including runtime and HTTP metrics.
	DisableMetrics bool

	// DisableRuntimeMetrics stops the Go runtime metrics (memory, GC,
	// goroutines) that are otherwise collected every 30 seconds.
	DisableRuntimeMetrics bool

	// LogLevel is the minimum level written locally and sent, for example
	// slog.LevelDebug or a *slog.LevelVar to change it at run time. nil
	// means slog.LevelInfo. Errors are always sent.
	LogLevel slog.Leveler

	// Output receives local log output. Defaults to os.Stderr. Use
	// io.Discard to log to Pingwright only. Ignored when Handler is set.
	Output io.Writer

	// TextOutput writes local output with slog's text format instead of JSON.
	// Ignored when Handler is set.
	TextOutput bool

	// Handler, when set, receives local log output instead of the built-in
	// JSON or text handler on Output. Its own level applies locally;
	// LogLevel still decides what is sent.
	Handler slog.Handler

	// KeepDefaultLogger leaves slog.Default alone. By default Init calls
	// slog.SetDefault(pingwright.Logger()), so slog.Info and the log package
	// go to Pingwright too.
	KeepDefaultLogger bool

	// ResourceAttributes are added to every log record and metric, for
	// example {"k8s.cluster.name": "eu-1"}. Service, Environment and Version
	// win over the same keys here. OTEL_RESOURCE_ATTRIBUTES is also read.
	ResourceAttributes map[string]string
}

Options configures Init. The zero value is valid: it reads the key from PINGWRIGHT_KEY and sends logs at Info and above, errors and metrics.

Directories

Path Synopsis
examples
basic command
Command basic is a small HTTP service that sends its logs, metrics and errors to Pingwright.
Command basic is a small HTTP service that sends its logs, metrics and errors to Pingwright.

Jump to

Keyboard shortcuts

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