Claude API Middleware for Request Logging
If you're searching for "Claude API middleware for request logging," you're probably trying to solve one of two problems: you need visibility into what your app is actually sending to Claude and getting back, or you're debugging a production issue and realized you have no record of the request that caused it. Either way, the answer is the same: insert a thin logging layer between your application code and the Anthropic API, so every call gets captured — prompt, response, token counts, latency, status — without touching your business logic every time you need a new field.
This article covers how to build that middleware yourself in Node.js, what fields actually matter for debugging and cost control, and how a hosted gateway like SubToAPI can give you most of this out of the box without maintaining your own logging code.
Why you need middleware, not scattered console.log calls
Most teams start logging Claude API calls by sprinkling console.log statements near the fetch call. This breaks down fast:
- Logs end up in different formats across endpoints
- Nobody captures latency or token usage consistently
- Sensitive data (full prompts, user PII) gets logged with no redaction policy
- When something fails in production, you have a stack trace but no idea what was actually sent to the model
Middleware solves this by wrapping every outbound request to the Messages API in a single function. You call that function everywhere instead of calling fetch directly, and all logging, retries, and metrics live in one place.
Building request-logging middleware for the Claude API
Here's a minimal example that wraps the Anthropic Messages endpoint with structured logging:
async function callClaude(payload, { requestId } = {}) {
const start = Date.now();
const id = requestId || crypto.randomUUID();
try {
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": process.env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify(payload),
});
const data = await res.json();
const durationMs = Date.now() - start;
logRequest({
id,
model: payload.model,
status: res.status,
durationMs,
inputTokens: data.usage?.input_tokens,
outputTokens: data.usage?.output_tokens,
stopReason: data.stop_reason,
error: res.ok ? null : data.error?.message,
});
if (!res.ok) throw new Error(data.error?.message || "Claude API error");
return data;
} catch (err) {
logRequest({
id,
model: payload.model,
status: "network_error",
durationMs: Date.now() - start,
error: err.message,
});
throw err;
}
}
function logRequest(entry) {
// Replace with your logging backend: stdout, Datadog, a database table, etc.
console.log(JSON.stringify({ ts: new Date().toISOString(), ...entry }));
}
This gets you consistent structured logs for every call, but notice what's missing: you still have to handle retries, rate limit backoff, redaction of sensitive prompt content, and persistence of logs somewhere queryable. Each of those is its own project.
What to actually log
Not every field belongs in your logs. A reasonable baseline:
- Request ID — generate or propagate one so you can correlate logs across services
- Model name — essential when you run multiple model versions side by side
- Token counts —
input_tokensandoutput_tokensfrom theusageobject, needed for cost tracking - Latency — time from request sent to response received
- Status code and error message — for debugging failures and rate limits
- Stop reason — tells you if the model hit
max_tokens, called a tool, or finished naturally
Think twice before logging full prompt and completion text in plain form, especially if your app handles user data. If you need it for debugging, store it encrypted or with a short retention window, and strip anything that looks like PII before it hits your log pipeline.
Middleware patterns that scale
Once the basic wrapper works, a few patterns make it more durable:
Separate the transport from the logging. Keep your fetch logic independent of your logging sink so you can swap from console.log to a database or log aggregator without touching request code.
Add a pre-request hook for redaction. Before logging the payload, strip or hash fields you don't want stored raw — user names, emails, anything from a form field.
Log retries as distinct events. If you retry on a 429 or 529, log each attempt separately with the same request ID so you can see retry storms in your dashboards.
Attach tool-use metadata. If you're using tool use, log which tool was called and with what arguments — this is often more useful for debugging than the raw text response.
When middleware you build isn't worth maintaining
Writing this wrapper is maybe an hour of work. The real cost is everything that comes after: alerting on error rate spikes, building a dashboard your team actually checks, handling multiple API keys for different environments, and keeping the logging schema consistent as your app grows.
If request logging, usage metadata, and team-level visibility are the actual goal — rather than the middleware code itself — a hosted gateway can save that maintenance burden. SubToAPI sits between your app and Claude, exposing a clean HTTPS API with sub_live_... application keys, and logs request-level usage metadata (tokens, latency, status) per key in a dashboard automatically. You get streaming, tool use, and the same Messages interface you'd build by hand, minus the logging and seat-management plumbing.
Plans run from Solo at €9 for individual projects to Team at €19/seat and Scale at €49/seat for larger orgs needing per-seat key isolation. You can start with a free trial at signup and check the quickstart to see how fast it is to swap in versus a self-built wrapper. See pricing for the full breakdown.
Whether you build the middleware yourself or adopt a gateway, the principle is the same: every Claude API call should pass through one controlled point where you can see what happened, measure what it cost, and catch failures before your users do.
questions
Does middleware add noticeable latency to Claude API calls? A well-written wrapper adds microseconds — it's just a function call around your existing fetch logic. Latency problems usually come from synchronous logging to slow external services; use async or buffered writes to avoid blocking the response.
Should I log the full prompt and response text? Only if you have a clear retention and redaction policy. Full text logging is useful for debugging but risky for privacy and storage costs — many teams log token counts and metadata by default, and only capture full content temporarily when actively investigating an issue.
Can I log requests without modifying every call site in my app? Yes, if you centralize all Claude API calls through one client function or use a gateway. That's the core reason to build middleware in the first place — instrumenting one place instead of every call site.