Dart
zharp_core and zharp_shelf trace every request a shelf, dart_frog or dart:io server handles, and send the errors of Dart servers, tools and desktop programs — each once, with the code that ran.
This SDK is new, and its API may still change before 1.0. Requires Dart 3.3 or later; for zharp_shelf, shelf 1.4 or later.
Plain Dart, no Flutter: zharp_core is the engine zharp_flutter runs on, and works on its own in any Dart program. zharp_shelf adds the middleware for shelf and dart_frog. A Flutter app — desktop included — uses zharp_flutter instead.
Quickest setup
In the project's folder, run the setup (it needs Node.js only to run). It opens a page to pick the Zharp app, runs dart pub add, and in a project as dart create made it runs main inside Zharp — with the middleware first on shelf. It shows every change before making it; the rest of this page is what it sets up, by hand.
npm init zharp@latest
Install
dart pub add zharp_core zharp_shelf
Without shelf (a dart:io server, a tool or a desktop program), zharp_core alone:
dart pub add zharp_core
Shelf servers
Start Zharp inside ZharpCore.run and put the middleware first. Each request gets a SERVER span that continues the caller's traceparent and carries its baggage (the user and session a Zharp front end sends); a handler that throws fails it, the error is reported in the request's trace, and shelf still answers 500.
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:zharp_core/zharp_core.dart';
import 'package:zharp_shelf/zharp_shelf.dart';
void main() => ZharpCore.run(() async {
ZharpCore.start(ZharpOptions(key: 'zpk_…', service: 'checkout-api', environment: 'production'));
final handler = Pipeline()
.addMiddleware(zharpMiddleware()) // first, so it sees everything
.addMiddleware(logRequests())
.addHandler(router.call);
await serve(handler, InternetAddress.anyIPv4, 8080);
});shelf_router doesn't tell middleware which route matched, so a span is named by its method until the handler says the route:
Response _order(Request request) {
setRequestRoute('/orders/<id>'); // the span reads GET /orders/<id>
// …
}dart_frog
dart_frog runs on shelf. Add the middleware, and start Zharp in a custom entrypoint (main.dart's run) before serve:
// routes/_middleware.dart import 'package:dart_frog/dart_frog.dart'; import 'package:zharp_shelf/zharp_shelf.dart'; Handler middleware(Handler handler) => handler.use(fromShelfMiddleware(zharpMiddleware()));
dart:io servers
Wrap the handler you pass to listen; setRequestRoute names its span the same way.
import 'dart:io';
import 'package:zharp_core/server.dart';
import 'package:zharp_core/zharp_core.dart';
void main() => ZharpCore.run(() async {
ZharpCore.start(ZharpOptions(key: 'zpk_…', service: 'checkout-api'));
final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
server.listen(zharpHandler((request) async {
request.response.write('ok');
await request.response.close();
}));
});Tools, workers and desktop programs
Run main inside ZharpCore.run. An error nothing catches is reported as fatal and sent (for up to three seconds) before the program ends as it would have — printed, exit code 255. A span around a job puts its logs, outgoing requests and errors in one trace. exit() ends the program at once, so call close() before it.
import 'package:zharp_core/zharp_core.dart';
void main(List<String> args) => ZharpCore.run(() async {
ZharpCore.start(ZharpOptions(key: 'zpk_…', service: 'price-import'));
await ZharpCore.instance?.startSpan('import prices', (span) async {
await importPrices(args.first);
});
await ZharpCore.instance?.close(); // send what's waiting
});Give ZharpCore.run an async function, as above: an error thrown in it then reaches Zharp too. A desktop app with a UI is a Flutter app — use zharp_flutter.
From the environment
On a server, the options can come from the environment instead: ZHARP_KEY, ZHARP_SERVICE, ZHARP_ENVIRONMENT and ZHARP_RELEASE fill in what ZharpOptions leaves unset.
ZHARP_KEY=zpk_… ZHARP_SERVICE=checkout-api ZHARP_ENVIRONMENT=production dart run bin/server.dart // then, in code: ZharpCore.start(const ZharpOptions());
Logs
Every line printed while a request is handled — print, stdout, stderr, so package:logging listeners, the logger package and shelf's request log too — ends with trace_id=… span_id=… (two fields in a JSON line). Where the Zharp agent reads the server's output, it brings those lines in and Zharp links each one to its request. ZHARP_LOG_CORRELATION=false turns the stamp off.
Where nothing reads the output, set ZHARP_LOGS=true (logs: true) and the SDK sends what the program prints and logs itself, each line in the span it was written in. Errors, traces and zharp.log calls are always sent.
Logs only
If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests. A request from a Zharp front end is still read, so its logs keep the caller's user, session and trace ID.
void main() => ZharpCore.run(() async {
ZharpCore.start(ZharpOptions(key: 'zpk_…', service: 'checkout-api', tracing: false, logs: true));
await serve();
});The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.
Errors
An error a request handler throws, and in ZharpCore.run any error nothing catches, is sent as unhandled with its Dart stack, once — the same error reaching a second handler isn't sent again. Report one you caught:
try {
await payments.charge(order);
} catch (error, stack) {
ZharpCore.instance?.captureError(error, stackTrace: stack, attributes: {'order_id': order.id});
}The stack is sent as the Dart VM writes it. Your frames — the app's own package and local path packages, as .dart_tool/package_config.json lists them — are told from shelf's, pub packages' and Zharp's, so the issue is named after the line in your code:
ArgumentError: Invalid argument (price): can't be negative: -5.0 #0 priceWithTax (package:shop_api/prices.dart:4:5) #1 _priceHandler (file:///app/bin/server.dart:24:25) #2 RouterEntry.invoke (package:shelf_router/src/router_entry.dart:146:7) …
The code that ran
Run from source (dart run), each error carries five lines either side of its innermost five frames in your code, read where the server runs — never the SDK's or pub packages' files. A compiled executable (dart compile exe, as the shelf template's Dockerfile builds) has no source beside it: its stack still names your files and lines, and the code comes from the linked repository. captureSourceContext: false (or ZHARP_CAPTURE_SOURCE_CONTEXT=false) turns it off.
Readable stack traces
Nothing to upload: the stacks this SDK sends already name your functions, files and lines, and issues are grouped by them.
Tracing
Requests made with ZharpHttpClient (package:http) or zharp_dio while handling a request are its children and pass the trace on to the APIs they call (those in tracingOrigins).
final zharp = ZharpCore.instance!;
zharp.log.info('Order placed', {'order_id': 42}); // sent whatever ZHARP_LOGS says
zharp.setTag('region', 'eu-west'); // on every span and log after
await zharp.startSpan('render invoice', (span) => render(invoice));
await zharp.flush(); // send nowUser context
Requests from the Zharp browser and mobile SDKs carry their user and session in baggage. When the server knows better, set it while handling the request — it is that request's user, not the process's:
ZharpCore.instance?.setUser(id: user.id, email: user.email); // this request's user
Options
| ZharpOptions | Environment | Default |
|---|---|---|
key | ZHARP_KEY | — (nothing is sent without one) |
service | ZHARP_SERVICE | unknown_service:dart |
environment | ZHARP_ENVIRONMENT | none |
release | ZHARP_RELEASE | none |
logs | ZHARP_LOGS | false. See Logs. |
logCorrelation | ZHARP_LOG_CORRELATION | true: lines printed in a request end with trace_id=… span_id=… |
captureSourceContext | ZHARP_CAPTURE_SOURCE_CONTEXT | true. See The code that ran. |
captureOutput | ZHARP_CAPTURE_OUTPUT | true: with logs on, what the program prints |
tracing | — | true; false sends errors and logs only |
sampleRate | — | 1.0 — share of traces kept; logs and errors are always sent |
Supported versions
- Dart 3.3 and later, on Linux, macOS and Windows.
- shelf 1.4 and later (zharp_shelf), dart_frog, and
dart:io'sHttpServer. - Serverpod isn't covered yet: its endpoints don't run through shelf. Wrap work in
startSpanmeanwhile.
Troubleshooting
Nothing arrives
On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:
- Is
initcalled, and before the code you expect to see? Without a key, the SDK starts nothing and says so once. - Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key,
servicedecides the app — see Keys. - Data is sent in batches every few seconds. A process that exits straight away should call
flushfirst. - Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
- Nothing from a tool that ends quickly? Await
ZharpCore.instance?.close()before the program ends or callsexit(). - An uncaught error isn't reported?
mainmust run insideZharpCore.run, with anasyncfunction.
401 or 403
Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.