Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(logging): capture request bodies in debug mode

Sidwebworks80984e37d523
diff --git a/packages/logger/AGENTS.md b/packages/logger/AGENTS.md
index 1a921580d4..6cce1b24c6 100644
--- a/packages/logger/AGENTS.md
+++ b/packages/logger/AGENTS.md
@@ -24,6 +24,15 @@ categories, env-driven levels, and cloud-agnostic request-id correlation.
(registered first in each app's `root.tsx`) puts `{ requestId }` into implicit
context, so every server log during a request carries it. Read it explicitly
with `getRequestId(context)` from `@carbon/logger/middleware.server`.
+- Request-body logging is **debug-only** and guarded: `requestIdMiddleware`
+ captures the body onto the access-log record's `body` prop **only** when
+ `LOG_LEVEL=debug` (skipped entirely at the prod `info` default — no clone, no
+ parse). It covers `POST/PUT/PATCH/DELETE` with `application/json` or
+ `application/x-www-form-urlencoded` bodies at/under 8KB (`content-length`
+ required); multipart uploads, oversized, and unknown-length bodies log a short
+ marker instead. Sensitive fields (`password`/`token`/`secret`/`email`/… — the
+ `DEFAULT_REDACT_FIELDS` set) are masked `[REDACTED]` in the captured object.
+ The body is read from a clone, so the route handler's stream stays intact.
## Ask First
diff --git a/packages/logger/src/http-formatter.ts b/packages/logger/src/http-formatter.ts
index dd37ce877e..d30b70f006 100644
--- a/packages/logger/src/http-formatter.ts
+++ b/packages/logger/src/http-formatter.ts
@@ -23,7 +23,7 @@ function statusColor(status: number): string {
*/
export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({
format({ timestamp, level, category, message, record }) {
- const { method, pathname, status, responseTime } = record.properties;
+ const { method, pathname, status, responseTime, body } = record.properties;
let line = message;
if (
@@ -37,6 +37,13 @@ export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({
? ` ${DIM}${Math.trunc(responseTime * 10) / 10} ms${RESET}`
: "";
line = `${BOLD}${method}${RESET} ${pathname} ${statusColor(status)}${status}${RESET}${time}`;
+ // The Morgan line only renders method/path/status/time, so a captured
+ // request body (debug only, already redacted) would otherwise be dropped
+ // in dev — append it dimmed on its own line.
+ if (body !== undefined) {
+ const rendered = typeof body === "string" ? body : JSON.stringify(body);
+ line += `\n ${DIM}body ${rendered}${RESET}`;
+ }
}
return `${timestamp ? `${timestamp} ` : ""}${level} ${category}: ${line}`;
diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.ts
index 63581ddc72..871d42fe96 100644
--- a/packages/logger/src/middleware.server.ts
+++ b/packages/logger/src/middleware.server.ts
@@ -1,4 +1,5 @@
import { withContext } from "@logtape/logtape";
+import { DEFAULT_REDACT_FIELDS } from "@logtape/redaction";
import { nanoid } from "nanoid";
import {
createContext,
@@ -9,6 +10,88 @@ import { getLogger } from "./logger";
export const REQUEST_ID_HEADER = "x-request-id";
+/** Only these carry a body worth logging; GET/HEAD/OPTIONS don't. */
+const BODY_LOG_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
+/**
+ * Cap on how large a body we'll buffer for logging. Bounds memory: we require a
+ * `content-length` at/under this before reading, so a 120MB CAD upload is never
+ * pulled into the log path.
+ */
+const BODY_LOG_MAX_BYTES = 8 * 1024;
+const REDACTED = "[REDACTED]";
+
+/** `DEFAULT_REDACT_FIELDS` entries are `string | RegExp`; match either form. */
+function isSensitiveKey(key: string): boolean {
+ return DEFAULT_REDACT_FIELDS.some((pattern) =>
+ typeof pattern === "string"
+ ? key.toLowerCase().includes(pattern.toLowerCase())
+ : pattern.test(key)
+ );
+}
+
+/**
+ * Recursively mask values whose key matches a sensitive-field pattern (the same
+ * `DEFAULT_REDACT_FIELDS` LogTape's `redactByField` uses: password/token/secret/
+ * key/auth/email/phone/address/…). The sink-level redactor only runs in prod
+ * (JSONL); debug bodies are captured in dev where it's off, so we redact the
+ * body value here directly.
+ */
+function redactBody(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(redactBody);
+ if (value && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value)) {
+ out[k] = isSensitiveKey(k) ? REDACTED : redactBody(v);
+ }
+ return out;
+ }
+ return value;
+}
+
+/**
+ * Best-effort capture of a request body for debug logging. Returns a redacted
+ * object for JSON / form-urlencoded bodies, a short marker string for skipped
+ * ones (multipart, oversized, unknown length), or `undefined` for methods /
+ * content-types we don't log. Never throws — a parse failure yields a marker.
+ *
+ * Reads a clone so the route handler's body stream stays intact.
+ */
+async function captureRequestBody(request: Request): Promise<unknown> {
+ if (!BODY_LOG_METHODS.has(request.method)) return undefined;
+
+ const contentType = request.headers.get("content-type") ?? "";
+ if (contentType.includes("multipart/form-data")) {
+ return "<multipart form-data not captured>";
+ }
+
+ const isJson = contentType.includes("application/json");
+ const isForm = contentType.includes("application/x-www-form-urlencoded");
+ if (!isJson && !isForm) return undefined;
+
+ // Require a known, bounded length so we never buffer an unbounded stream.
+ const lengthHeader = request.headers.get("content-length");
+ if (lengthHeader === null) return "<unknown length not captured>";
+ const length = Number(lengthHeader);
+ if (!Number.isFinite(length)) return "<unknown length not captured>";
+ if (length > BODY_LOG_MAX_BYTES) return `<${length} bytes not captured>`;
+ if (length === 0) return undefined;
+
+ try {
+ if (isForm) {
+ const form = await request.clone().formData();
+ const obj: Record<string, unknown> = {};
+ for (const [k, v] of form.entries()) {
+ obj[k] = typeof v === "string" ? v : "<file>";
+ }
+ return redactBody(obj);
+ }
+ const text = await request.clone().text();
+ return redactBody(JSON.parse(text));
+ } catch {
+ return "<unparseable body>";
+ }
+}
+
/** Request-scoped correlation id, readable in loaders/actions via `getRequestId`. */
export const requestIdContext = createContext<string | null>(null);
@@ -38,17 +121,26 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (
const { pathname } = new URL(request.url);
const start = performance.now();
+ // Capture the body only when debug is actually enabled — skips the clone +
+ // parse entirely at the prod `info` default. Done before `next()` so the
+ // clone happens while the stream is untouched.
+ const body = log.isEnabledFor("debug")
+ ? await captureRequestBody(request)
+ : undefined;
+
const response = await withContext({ requestId }, async () => {
const res = await next();
// Debug-level so it is visible in dev but filtered by the prod `info`
// default — the pipeline is observable with zero migrated call sites.
// Rendered as a Morgan "dev"-style colored line in dev (see
- // http-formatter.ts) and as a structured JSONL record in prod.
+ // http-formatter.ts) and as a structured JSONL record in prod. When a
+ // request body was captured, it rides on the same record (`body`).
log.debug("{method} {pathname} → {status} in {responseTime}ms", {
method,
pathname,
status: res.status,
- responseTime: performance.now() - start
+ responseTime: performance.now() - start,
+ ...(body === undefined ? {} : { body })
});
return res;
});
diff --git a/packages/logger/src/middleware.test.ts b/packages/logger/src/middleware.test.ts
index cdafce1b55..97753f92a9 100644
--- a/packages/logger/src/middleware.test.ts
+++ b/packages/logger/src/middleware.test.ts
@@ -88,3 +88,117 @@ describe("requestIdMiddleware", () => {
expect(record?.properties.requestId).toBe("trace-me");
});
});
+
+function httpRecord() {
+ return recorder.records.find((r) => r.category.join(".") === "carbon.http");
+}
+
+function jsonRequest(body: string) {
+ return new Request("http://x/action", {
+ method: "POST",
+ body,
+ headers: {
+ "content-type": "application/json",
+ "content-length": String(new TextEncoder().encode(body).length)
+ }
+ });
+}
+
+describe("requestIdMiddleware body logging", () => {
+ it("captures a JSON body and redacts sensitive fields", async () => {
+ const request = jsonRequest(
+ JSON.stringify({
+ name: "Widget",
+ password: "hunter2",
+ nested: { token: "t" }
+ })
+ );
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+
+ const body = httpRecord()?.properties.body as Record<string, unknown>;
+ expect(body).toBeDefined();
+ expect(body.name).toBe("Widget");
+ expect(body.password).toBe("[REDACTED]");
+ expect((body.nested as Record<string, unknown>).token).toBe("[REDACTED]");
+ });
+
+ it("leaves the body stream intact for the handler", async () => {
+ const request = jsonRequest(JSON.stringify({ hello: "world" }));
+ let handlerSaw: unknown;
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => {
+ handlerSaw = await request.json();
+ return new Response("ok");
+ }
+ );
+ expect(handlerSaw).toEqual({ hello: "world" });
+ });
+
+ it("captures a form-urlencoded body and redacts sensitive fields", async () => {
+ const body = "email=a%40b.com&note=hi";
+ const request = new Request("http://x/action", {
+ method: "POST",
+ body,
+ headers: {
+ "content-type": "application/x-www-form-urlencoded",
+ "content-length": String(body.length)
+ }
+ });
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ const captured = httpRecord()?.properties.body as Record<string, unknown>;
+ expect(captured.email).toBe("[REDACTED]");
+ expect(captured.note).toBe("hi");
+ });
+
+ it("skips multipart bodies", async () => {
+ const request = new Request("http://x/upload", {
+ method: "POST",
+ body: "----x",
+ headers: {
+ "content-type": "multipart/form-data; boundary=x",
+ "content-length": "5"
+ }
+ });
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ expect(httpRecord()?.properties.body).toBe(
+ "<multipart form-data not captured>"
+ );
+ });
+
+ it("skips oversized bodies by content-length", async () => {
+ const request = new Request("http://x/action", {
+ method: "POST",
+ body: "{}",
+ headers: {
+ "content-type": "application/json",
+ "content-length": String(64 * 1024)
+ }
+ });
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ expect(httpRecord()?.properties.body).toBe(
+ `<${64 * 1024} bytes not captured>`
+ );
+ });
+
+ it("adds no body for GET requests", async () => {
+ const request = new Request("http://x/dashboard");
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ expect(httpRecord()?.properties.body).toBeUndefined();
+ });
+});