zharp

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 28 Imported by: 0

README

zharp-go-lib

Zharp Application Monitoring for Go: every request traced, logs sent with their trace, panics and errors grouped into issues. A thin layer over the official OpenTelemetry Go SDK — zharp.Init configures the OTLP/HTTP exporters, resource, W3C tracecontext + baggage propagation and a log/slog bridge, and sets the global providers, so any OpenTelemetry instrumentation in your app is sent too.

Full documentation: zharp.io/docs/sdks/go

Install

go get github.com/zharp-io/zharp-go-lib
import zharp "github.com/zharp-io/zharp-go-lib"

Start it

shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Environment: "production"})
defer shutdown(context.Background())

Copy the key from Applications → your app → Setup in Zharp. Leave fields empty to read them from ZHARP_KEY, ZHARP_SERVICE (then OTEL_SERVICE_NAME), ZHARP_ENVIRONMENT, ZHARP_RELEASE, ZHARP_ENDPOINT, ZHARP_SAMPLE_RATE, ZHARP_TRACING. ZHARP_DISABLED=true turns it off. Init never panics: without a key it prints one line and sends nothing.

Trace requests

net/http

http.ListenAndServe(":8080", zharp.Handler(mux))

Gin — go get github.com/zharp-io/zharp-go-lib/zharpgin

router.Use(zharpgin.Middleware())

Echo (v4) — go get github.com/zharp-io/zharp-go-lib/zharpecho

e.Use(zharpecho.Middleware())

Each request becomes one SERVER span named by its route (GET /orders/{id}), continuing the caller's trace from traceparent. The user and session a Zharp front-end SDK sends in baggage (enduser.id, session.id) go on every span and log of the request. A panic is reported as an unhandled error (and answered with a 500 by zharp.Handler; Gin and Echo keep their own recovery); so is an error a Gin/Echo handler returns that ends in a 5xx.

Outgoing calls: &http.Client{Transport: zharp.Transport(nil)}, with http.NewRequestWithContext. Gin and Echo live in their own modules, so the core module doesn't pull them in.

Logs

slog is bridged: after Init, slog.InfoContext(ctx, …) — and the log package — prints as before and goes to Zharp with the request's trace (use the …Context variants). To log to Zharp only:

zharp.Log.Info(ctx, "Order placed", "order_id", 42)   // Debug, Info, Warn, Error, Fatal

Config.KeepSlogDefault leaves slog.Default alone; zharp.SlogHandler() gives you the handler.

Logs only

To send logs and errors without tracing:

shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", DisableTracing: true})

or ZHARP_TRACING=false. Logs (zharp.Log, slog, log), errors (panics, 5xx handler errors, CaptureError, with the handled flag), SetUser and SetTag work as usual. No spans are created or sent: zharp.Handler, zharpgin and zharpecho make none, zharp.Tracer() spans record nothing (the code inside still runs), and zharp.Transport and the global propagator add no traceparent or baggage to outgoing requests. Incoming traceparent and baggage are still read, so a request's logs and errors carry the caller's trace id, user and session.

Errors

if err := charge(ctx, order); err != nil {
	zharp.CaptureError(ctx, err, "order_id", order.ID)   // handled
}

Go has no global panic hook: defer zharp.Recover() at the top of main and in goroutines reports a panic (fatal), sends it, and panics again.

More

ctx = zharp.SetUser(ctx, zharp.User{ID: account.ID})   // this request's user, when the server knows better
zharp.SetTag("region", "eu-west")                      // on every span and log after
ctx, span := zharp.Tracer().Start(ctx, "render invoice")
defer span.End()
zharp.Flush(ctx)                                       // send now (serverless, end of a job)

Telemetry is batched (5 s), gzip-compressed and retried by the OpenTelemetry exporters.

Development

go test ./... && (cd zharpgin && go test ./...) && (cd zharpecho && go test ./...)
ZHARP_KEY=zpk_… ZHARP_ENDPOINT=http://localhost:3000/api/v1/otlp go run ./examples/nethttp

zharpgin and zharpecho are separate modules with a replace to the core in this repo; release them with their own tags (zharpgin/v0.2.0, zharpecho/v0.2.0) after tagging the core (v0.2.0).

License

MIT © Zharp

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

View Source
const DefaultEndpoint = "https://api.zharp.io/api/v1/otlp"

DefaultEndpoint is where telemetry goes unless Config.Endpoint or ZHARP_ENDPOINT says otherwise.

View Source
const Version = "0.2.0"

Version is this module's version, sent as telemetry.sdk.version.

Variables

View Source
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

func CaptureError(ctx context.Context, err error, args ...any)

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

func Flush(ctx context.Context) error

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

func Handler(h http.Handler) http.Handler

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

func Init(cfg Config) func(context.Context) error

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

func ReportPanic(ctx context.Context, value any)

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

func ReportUnhandledError(ctx context.Context, err error)

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

func SetUser(ctx context.Context, user User) context.Context

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

func SlogHandler() slog.Handler

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

func Tracer() trace.Tracer

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.

type User added in v0.2.0

type User struct {
	ID    string
	Email string
	Name  string
}

User is who a request is for.

Directories

Path Synopsis
examples
nethttp command
A net/http server with Zharp.
A net/http server with Zharp.
zharpecho module
zharpgin module
zharpzap module

Jump to

Keyboard shortcuts

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