auto-api-observe
v1.2.0
Published
Zero-config observability middleware for Express and Fastify — request tracing, slow API detection, metrics, and structured JSON logs.
Maintainers
Readme
The Problem
You ship an Express/Fastify API. It works. Then you need to know:
- Which routes are slowest?
- What's your error rate?
- How many DB calls per request?
- Is that new endpoint actually being used?
Setting up Datadog costs $23/host/month. New Relic wants your credit card. Grafana needs a PhD to configure.
The Solution
app.use(require('auto-api-observe')()); // done.That's it. Every request is now tracked with structured JSON logs, trace IDs, latency, DB call counts, and slow request detection.
Why APILens?
| Feature | auto-api-observe | Datadog | New Relic | Sentry | |---|:---:|:---:|:---:|:---:| | Setup time | 10 seconds | 30+ min | 30+ min | 15+ min | | Lines of code | 1 | 20+ | 15+ | 10+ | | Dependencies | 0 | 50+ | 40+ | 30+ | | Free tier | 1k req/day forever | 14-day trial | 100GB/mo | 5k events | | Pricing | $0 – $29/mo | $23/host/mo | $0.30/GB | $26/mo | | DB call tracking | Built-in | Custom instrumentation | Custom instrumentation | No | | Config required | None | Agent + YAML | Agent + config | DSN + config |
Install
npm install auto-api-observeQuick Start
Express (1 line)
const express = require('express');
const observe = require('auto-api-observe');
const app = express();
app.use(observe()); // <-- that's it
app.get('/users', (req, res) => res.json({ users: [] }));
app.listen(3000);Fastify (1 line)
const fastify = require('fastify')();
const { fastifyObservability } = require('auto-api-observe');
await fastify.register(fastifyObservability); // <-- that's it
fastify.get('/users', async () => ({ users: [] }));
await fastify.listen({ port: 3000 });What You Get Instantly
Every request automatically outputs:
{
"timestamp": "2026-03-17T12:00:00.000Z",
"traceId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"method": "GET",
"route": "/users",
"status": 200,
"latency": 42,
"latencyMs": "42ms",
"dbCalls": 0,
"slow": false,
"ip": "127.0.0.1"
}Features
- Structured JSON logs — every response emits a clean JSON entry
- Distributed trace IDs — auto-generated UUID per request, forwarded via
x-trace-id - Slow request detection — requests above a configurable threshold flagged
slow: true - DB call counting — call
trackDbCall()anywhere in your async chain - In-memory metrics — aggregated per-route stats via
getMetrics() - Custom fields — attach arbitrary data to any request with
addField() - High throughput — buffered async logger, benchmarked at 600k+ req/min
- Sampling — log only a fraction of requests via
sampleRateat extreme volume - Memory safe —
maxRoutescap prevents unbounded growth from bot traffic - TypeScript-first — full type definitions included
- Zero dependencies — pure Node.js
Track DB Calls
const { trackDbCall } = require('auto-api-observe');
async function getUser(id) {
trackDbCall(); // automatically counts for current request
return db.query('SELECT * FROM users WHERE id = ?', [id]);
}Your logs will show "dbCalls": 3 when a route makes 3 queries. Spot N+1 problems instantly.
Add Custom Fields
const { addField } = require('auto-api-observe');
app.get('/orders', async (req, res) => {
const orders = await getOrders(req.user.id);
addField('userId', req.user.id);
addField('orderCount', orders.length);
res.json(orders);
});Get Metrics
const { getMetrics } = require('auto-api-observe');
app.get('/metrics', (req, res) => res.json(getMetrics()));Returns:
{
"totalRequests": 1420,
"successRequests": 1350,
"errorRequests": 40,
"slowRequests": 12,
"uptime": 3600,
"routes": {
"GET /users": { "count": 800, "avgLatency": 95, "errors": 0, "slowCount": 1 },
"POST /orders": { "count": 320, "avgLatency": 210, "errors": 4, "slowCount": 3 }
}
}Cloud Dashboard (Optional)
Connect to the APILens dashboard for charts, error logs, alerts, and weekly reports:
app.use(observe({
apiKey: process.env.APILENS_KEY, // get one free at apilens.rest
}));What you get:
- Real-time overview — requests, error rate, P95 latency, timeline charts
- Per-route breakdown — calls, avg latency, error count
- Error log — paginated 4xx/5xx with trace IDs
- Slow request log — ordered by latency
- Usage tracking — daily quota with overage alerts
- Alerts — email or Slack when error rate or latency spikes
Free tier: 1,000 requests/day — no credit card, no time limit.
All Options
observe({
// Local
slowThreshold: 1000, // ms — flag requests above this as slow
logger: console.log, // custom log fn, or `false` to silence
enableMetrics: true, // collect in-memory metrics
skipRoutes: ['/health'], // skip these routes (string prefix or RegExp)
traceHeader: 'x-trace-id', // header for trace ID propagation
maxRoutes: 1000, // cap on distinct routes in metrics
sampleRate: 1.0, // 0.0–1.0, fraction of requests to log
onRequest: (ctx) => {}, // called at start of each request
onResponse: (entry) => {}, // called after each response
// Cloud dashboard
apiKey: 'sk_live_...', // enables remote shipping
endpoint: 'https://...', // override for self-hosted
flushInterval: 5000, // ms between batch flushes
flushSize: 100, // flush when queue hits this size
});Distributed Tracing
Trace IDs propagate automatically across services:
Service A (generates traceId abc-123)
→ Service B (reads x-trace-id, reuses abc-123)
→ Service C (same ID — full chain visible in logs)Access it in your handler:
app.get('/items', (req, res) => {
console.log(req.traceId); // 'abc-123'
res.json({});
});TypeScript
import observe, {
ObservabilityOptions,
LogEntry,
Metrics,
trackDbCall,
addField,
getMetrics,
} from 'auto-api-observe';
app.use(observe({
slowThreshold: 500,
onResponse: (entry: LogEntry) => {
if (entry.slow) alertTeam(entry);
},
}));Examples
npm run example:express # local logs only
npm run example:fastify # local logs only
npm run example:cloud # stream to APILens dashboard
npm run example:advanced # custom logger, trackDbCall, addFieldContributing
Contributions welcome! Please open an issue first to discuss what you'd like to change.
git clone https://github.com/rahhuul/auto-api-observe.git
cd auto-api-observe
npm install
npm test # 34 testsLicense
MIT — use it however you want.
