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 Bool(v bool) *bool
- 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 LogIDs(ctx context.Context) (traceID, spanID string, ok bool)
- func LoggerProvider() otellog.LoggerProvider
- 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 StampLine(ctx context.Context, line []byte) []byte
- func Tracer() trace.Tracer
- func Transport(base http.RoundTripper) http.RoundTripper
- func WrapSlogHandler(h slog.Handler) slog.Handler
- type BodyMode
- type CaptureBodies
- type Config
- type RequestBodies
- func (b *RequestBodies) End(span trace.Span, status int)
- func (b *RequestBodies) Request(body io.ReadCloser) io.ReadCloser
- func (b *RequestBodies) ResponseWriter(w http.ResponseWriter) http.ResponseWriter
- func (b *RequestBodies) Status() int
- func (b *RequestBodies) Wrote(p []byte, header http.Header)
- type User
Constants ¶
const DefaultEndpoint = "https://api.zharp.io/api/v1/otlp"
DefaultEndpoint is where telemetry goes.
const Version = "0.4.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)
It is sent whatever Config.Logs says. slog's default is stamped after Init — slog.InfoContext prints with the request's trace_id and span_id at the end — and, with Config.Logs on, sent too.
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 LogIDs ¶ added in v0.4.0
LogIDs returns the trace and span ids to stamp on a line logged with ctx: ok is false outside a request, before Init, or with LogCorrelation off. For logging integrations.
func LoggerProvider ¶ added in v0.4.0
func LoggerProvider() otellog.LoggerProvider
LoggerProvider returns an OpenTelemetry LoggerProvider that sends to whichever Init is active when a record is emitted, if its Config.Logs is on (nothing before Init or with Logs off) — for logging bridges such as otelzap and otellogrus. Unlike global.GetLoggerProvider, loggers made from it before Init, or before Init is called again, follow the current one. The zharpzap, zharplogrus and zharpzerolog modules use it.
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 StampLine ¶ added in v0.4.0
StampLine returns a formatted log line ending with " trace_id=… span_id=…" — or, for a JSON record, with "trace_id" and "span_id" fields — when ctx is in a request (see LogIDs). A line that already mentions trace_id, a blank line and the tail of a JSON record are returned as they are; a trailing newline is kept. For logging integrations whose formatter can't add fields.
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.
func WrapSlogHandler ¶ added in v0.4.0
WrapSlogHandler returns h stamped and sending: each record logged during a request is printed by h with trace_id and span_id as its last attributes (unless LogCorrelation is off or it has a trace_id already), and, with Config.Logs on, sent to Zharp first. For a logger of your own, or a slog.SetDefault made after Init:
slog.SetDefault(slog.New(zharp.WrapSlogHandler(slog.NewJSONHandler(os.Stdout, nil))))
It may be made before Init: it follows whichever Init is active when a record is logged (and does nothing extra before Init). Records keep the trace and span of the context they are logged with (slog.InfoContext). A nil h only sends.
Types ¶
type BodyMode ¶ added in v0.3.0
type BodyMode int
BodyMode says which requests have their bodies captured.
type CaptureBodies ¶ added in v0.3.0
type CaptureBodies struct {
// Mode is BodiesErrors (the default: failed requests only) or BodiesAll.
Mode BodyMode
// MaxSize is the number of characters kept per body. Default 32768 (32 KB), at most 131072.
MaxSize int
// RedactKeys are more keys whose values are replaced with "[Filtered]", on top of the
// built-in ones. They match a key ignoring case, '-' and '_' ("accountNumber" also covers
// account_number).
RedactKeys []string
// RedactPatterns are tested against keys as they are; a match is filtered.
RedactPatterns []*regexp.Regexp
// URLs limits capture to these requests (incoming and outgoing): a bare host
// ("api.example.com") matches that host, a string with a scheme matches URLs starting with
// it. URLPatterns are tested against the full URL. Both empty: every request.
URLs []string
URLPatterns []*regexp.Regexp
}
CaptureBodies puts request and response bodies on HTTP spans — incoming requests (Handler, zharpgin, zharpecho) and outgoing calls (Transport). Set Config.CaptureBodies to turn it on; ZHARP_CAPTURE_BODIES=errors|all does the same without code.
Text is kept up to MaxSize; files in uploads, inline images and binary bodies are described (name, type, size), never sent. Field names are always kept; values under secret-looking keys (password, token, authorization, card, …) are replaced with "[Filtered]" before anything is sent. Other personal data in a body is sent as it is: add its keys to RedactKeys.
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 for Zharp's own testing; leave it empty.
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
// CaptureBodies puts request and response bodies on HTTP spans (Handler, Transport, zharpgin,
// zharpecho). Nil, the default, is off; ZHARP_CAPTURE_BODIES=errors|all turns it on without
// code. See CaptureBodies.
CaptureBodies *CaptureBodies
// Logs sends what the app logs — slog, the log package, and zap/logrus/zerolog through the
// zharpzap/zharplogrus/zharpzerolog modules — to Zharp. Nil, the default, is off, unless
// ZHARP_LOGS=true: where the Zharp agent reads the app's output (a server, a pod) it already
// brings those lines in, stamped with their request (see LogCorrelation), and sending them too
// would make every line arrive twice. Turn it on where there is no agent, such as serverless.
// Errors, traces and zharp.Log calls are sent either way.
//
// Logs: zharp.Bool(true)
Logs *bool
// LogCorrelation stamps every line logged during a request with the request's ids: a text line
// ends with " trace_id=<32 hex> span_id=<16 hex>", a JSON line gets "trace_id" and "span_id"
// fields. The agent's copy of the line is then linked to its request. It covers slog (and the
// log package's default logger), WrapSlogHandler and the zharpzap/zharplogrus/zharpzerolog
// modules; lines printed with fmt can't be stamped. Lines outside a request and lines that
// already carry a trace_id are left alone. Nil, the default, is on, unless
// ZHARP_LOG_CORRELATION=false.
LogCorrelation *bool
// KeepSlogDefault leaves slog's default logger alone: its lines are neither stamped nor sent.
// By default Init makes slog.Default (and so the log package) print as before — with the stamp
// — and, with Logs on, also send to Zharp.
KeepSlogDefault bool
// CaptureOutput (only with Logs on) also sends every line printed to os.Stdout and os.Stderr — fmt.Println, a
// log.Logger or zap/zerolog/logrus logger writing to them, anything — that the exact captures
// (slog, the log package, zharpzap, zharplogrus, zharpzerolog) didn't already send. Each line
// still prints exactly as before. Its level is read from the line (a JSON record's level,
// level=error, ERROR, [warn], klog's E1117…); otherwise stdout is info and stderr a warning. A
// line an exact capture already sent is not sent again. Off by default:
// ZHARP_CAPTURE_OUTPUT=true turns it on without code. Init swaps os.Stdout and os.Stderr for
// pipes, so: call Init first thing in main; a line printed right before os.Exit can be lost;
// code that checks for a terminal sees a pipe (no colours); and a printed line carries no
// request unless it is JSON with its own trace_id. See the README.
CaptureOutput 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_SAMPLE_RATE, ZHARP_TRACING, ZHARP_CAPTURE_BODIES, ZHARP_LOGS, ZHARP_LOG_CORRELATION, ZHARP_CAPTURE_OUTPUT — then defaulted.
type RequestBodies ¶ added in v0.3.0
type RequestBodies struct {
// contains filtered or unexported fields
}
RequestBodies records one incoming request's bodies for its span, when Config.CaptureBodies is on. It is for router integrations (zharpgin, zharpecho); Handler uses it already. A nil *RequestBodies (bodies off, or the URL not in CaptureBodies.URLs) does nothing.
func CaptureRequestBodies ¶ added in v0.3.0
func CaptureRequestBodies(r *http.Request) *RequestBodies
CaptureRequestBodies starts recording r's bodies. It returns nil when there is nothing to do.
func (*RequestBodies) End ¶ added in v0.3.0
func (b *RequestBodies) End(span trace.Span, status int)
End puts the bodies on span, if the status says they are wanted. Call it once, before the span ends.
func (*RequestBodies) Request ¶ added in v0.3.0
func (b *RequestBodies) Request(body io.ReadCloser) io.ReadCloser
Request returns the body the handler should read: every byte as before, with a copy of the first ones kept.
func (*RequestBodies) ResponseWriter ¶ added in v0.3.0
func (b *RequestBodies) ResponseWriter(w http.ResponseWriter) http.ResponseWriter
ResponseWriter returns w with what is written to it recorded; every interface w implements (Flusher, Hijacker, Pusher, ReaderFrom) is kept.
func (*RequestBodies) Status ¶ added in v0.3.0
func (b *RequestBodies) Status() int
Status is the status the response was sent with (200 if the handler set none).