Documentation
¶
Overview ¶
Package zharp is Zharp Application Monitoring for Go: a thin layer over the official OpenTelemetry SDK that sends traces, logs and errors to Zharp.
func main() {
shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Environment: "production"})
defer shutdown(context.Background())
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", getOrder)
http.ListenAndServe(":8080", zharp.Handler(mux))
}
Init configures OpenTelemetry — OTLP/HTTP exporters, resource, W3C tracecontext + baggage propagation, and a log/slog bridge — and sets the global providers, so any OpenTelemetry instrumentation in the app is sent too. Handler traces net/http requests; the zharpgin and zharpecho modules do the same for Gin and Echo.
Index ¶
- Constants
- Variables
- func CaptureError(ctx context.Context, err error, args ...any)
- func Flush(ctx context.Context) error
- func Handler(h http.Handler) http.Handler
- func Init(cfg Config) func(context.Context) error
- func Recover()
- func RecoverRequest(w http.ResponseWriter, r *http.Request)
- func ReportPanic(ctx context.Context, value any)
- func ReportUnhandledError(ctx context.Context, err error)
- func SetTag(key, value string)
- func SetUser(ctx context.Context, user User) context.Context
- func SlogHandler() slog.Handler
- func Tracer() trace.Tracer
- func Transport(base http.RoundTripper) http.RoundTripper
- type Config
- type User
Constants ¶
const DefaultEndpoint = "https://api.zharp.io/api/v1/otlp"
DefaultEndpoint is where telemetry goes unless Config.Endpoint or ZHARP_ENDPOINT says otherwise.
const Version = "0.2.0"
Version is this module's version, sent as telemetry.sdk.version.
Variables ¶
var Log logger
Log sends logs to Zharp only (not the console), with the trace, user and session of ctx. Arguments after the message are slog-style key-value pairs:
zharp.Log.Info(ctx, "Order placed", "order_id", 42)
slog is bridged too: after Init, slog.InfoContext(ctx, …) (and the log package) goes to the console as before and to Zharp. Use the *Context variants so logs carry the request's trace.
Functions ¶
func CaptureError ¶
CaptureError reports an error you handled. It becomes a Zharp issue (marked handled) with the request's trace, user and session. Extra attributes are slog-style key-value pairs:
if err := charge(ctx, order); err != nil {
zharp.CaptureError(ctx, err, "order_id", order.ID)
}
func Flush ¶
Flush sends everything queued now — before a serverless function returns, or at the end of a job. It waits until ctx is done at most.
func Handler ¶ added in v0.2.0
Handler traces every request to h — one SERVER span each, continuing the caller's trace from its traceparent header, named by the ServeMux pattern ("GET /orders/{id}") — and turns a panic into an unhandled error report and a 500.
http.ListenAndServe(":8080", zharp.Handler(mux))
It is otelhttp.NewHandler with Zharp's panic handling and http.route inside it. With Config.DisableTracing it makes no span: it only reads traceparent and baggage, so the request's logs and errors carry its trace_id, user and session, and still reports panics.
func Init ¶
Init starts sending to Zharp and returns the function that sends what's left and stops; call it on the way out:
shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api"})
defer shutdown(context.Background())
It never panics and never fails the app: without a key, or on a setup error, it writes one line to stderr and returns a shutdown that does nothing. ZHARP_DISABLED=true turns it off.
func Recover ¶
func Recover()
Recover reports a panic (unhandled, fatal), waits up to two seconds for it to be sent, then panics again so the program ends as it would have. Defer it first thing in main and in goroutines whose panics you want to see — Go has no global panic hook:
defer zharp.Recover()
func RecoverRequest ¶ added in v0.2.0
func RecoverRequest(w http.ResponseWriter, r *http.Request)
RecoverRequest is the panic handling of Handler, for middleware of other routers: deferred inside the request's span, it reports a panic (unhandled), marks the span as failed and answers 500. http.ErrAbortHandler is re-panicked, as net/http expects.
defer zharp.RecoverRequest(w, r)
func ReportPanic ¶ added in v0.2.0
ReportPanic reports a recovered panic value as an unhandled error, with the stack of the panicking goroutine. Call it in a deferred function, right after recover().
func ReportUnhandledError ¶ added in v0.2.0
ReportUnhandledError reports an error that ended a request with a 5xx — what a router does with an error a handler returned. For router integrations (zharpgin, zharpecho); in your own code use CaptureError. A returned error carries no stack, so it is grouped by type and message.
func SetTag ¶ added in v0.2.0
func SetTag(key, value string)
SetTag puts an attribute on every span and log from now on, across the program. An empty value removes it.
func SetUser ¶ added in v0.2.0
SetUser returns a context whose spans and logs carry this user (enduser.id, enduser.email, enduser.name), and puts it on the span already in ctx. A front end using a Zharp SDK sends its user with each request, so this is for when the server knows better:
ctx := zharp.SetUser(r.Context(), zharp.User{ID: account.ID})
r = r.WithContext(ctx)
func SlogHandler ¶ added in v0.2.0
SlogHandler returns a slog.Handler that sends to Zharp, for building your own logger — e.g. to send one logger's records without changing slog's default. Nil before Init.
func Tracer ¶ added in v0.2.0
Tracer returns a tracer for spans of your own: zharp.Tracer().Start(ctx, "render invoice"). With DisableTracing its spans record nothing (the code inside still runs, and its logs carry the incoming trace_id, if any).
func Transport ¶ added in v0.2.0
func Transport(base http.RoundTripper) http.RoundTripper
Transport traces outgoing requests (CLIENT spans) and sends traceparent with them:
client := &http.Client{Transport: zharp.Transport(nil)}
Use the request's context (http.NewRequestWithContext) so the call joins its trace. With Config.DisableTracing requests go straight to base: no span, no traceparent, no baggage.
Types ¶
type Config ¶
type Config struct {
// Key is the app's key (zpk_…) from Applications → your app → Setup. Without one, nothing
// is sent.
Key string
// Service is the service.name everything is filed under. Defaults to the last part of the
// main module's path (github.com/acme/checkout-api → checkout-api).
Service string
// Environment, e.g. "production".
Environment string
// Release, e.g. "api@2.3.0" — the service.version.
Release string
// Endpoint is the OTLP base URL. Defaults to https://api.zharp.io/api/v1/otlp.
Endpoint string
// SampleRate is the share of traces kept, 0 < rate ≤ 1. Zero means 1 (keep all). Logs and
// errors are always sent.
SampleRate float64
// DisableTracing sends logs and errors only ("logs only"): no spans are created or exported,
// Handler, Transport and the zharpgin/zharpecho middleware trace nothing, and no traceparent or
// baggage is sent with outgoing requests. An incoming traceparent and baggage are still read,
// so the logs and errors of a request carry its trace_id, user and session. Logs, errors,
// SetUser and SetTag work as usual. ZHARP_TRACING=false does the same.
DisableTracing bool
// KeepSlogDefault leaves slog's default logger alone. By default Init makes slog.Default
// (and so the log package) write to the console as before and also send to Zharp.
KeepSlogDefault bool
// SpanExporter and LogExporter replace the OTLP/HTTP exporters to Zharp, and export each span
// and log synchronously as it ends — for tests (tracetest.NewInMemoryExporter).
SpanExporter sdktrace.SpanExporter
LogExporter sdklog.Exporter
}
Config holds the settings for Init. Anything left empty is read from the environment — ZHARP_KEY, ZHARP_SERVICE (then OTEL_SERVICE_NAME), ZHARP_ENVIRONMENT, ZHARP_RELEASE, ZHARP_ENDPOINT, ZHARP_SAMPLE_RATE, ZHARP_TRACING — then defaulted.