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)
}
Output:
Index ¶
- Constants
- Variables
- func CaptureError(ctx context.Context, err error, attrs ...slog.Attr)
- func Init(ctx context.Context, opts Options) (shutdown func(context.Context) error, err error)
- func Logger() *slog.Logger
- func Meter(name string, opts ...metric.MeterOption) metric.Meter
- func Middleware(next http.Handler) http.Handler
- func Recover(ctx context.Context)
- type Options
Examples ¶
Constants ¶
const DefaultEndpoint = "https://ingest.pingwright.app"
DefaultEndpoint is where telemetry goes unless Options.Endpoint or PINGWRIGHT_ENDPOINT says otherwise.
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).
const Version = "0.1.0"
Version is the version of this library, reported as the instrumentation scope version.
Variables ¶
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 ¶
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") }
Output:
func Init ¶
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 ¶
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)
}
Output:
func Middleware ¶
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)))
}
Output:
func Recover ¶
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) {}
Output:
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.