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): log query string, reformat http dev line

Sidwebworks075ad2ee4030
diff --git a/packages/logger/src/http-formatter.test.ts b/packages/logger/src/http-formatter.test.ts
index 6c973c8377..de751809af 100644
--- a/packages/logger/src/http-formatter.test.ts
+++ b/packages/logger/src/http-formatter.test.ts
@@ -13,12 +13,30 @@ function record(properties: Record<string, unknown>) {
}
describe("httpDevFormatter", () => {
- it("keeps the standard timestamp/level/category prefix", () => {
+ it("renders a pino-style time-only / level / pid / module prefix", () => {
const line = httpDevFormatter(
record({ method: "GET", pathname: "/dashboard", status: 200 })
);
- expect(line).toContain("DBG");
- expect(line).toContain("carbon·http");
+ // [HH:MM:SS.mmm] — time only, no date.
+ expect(line).toMatch(/\[\d{2}:\d{2}:\d{2}\.\d{3}\]/);
+ // Uppercase level, pid, and the `carbon`-stripped module.
+ expect(line).toContain("DEBUG");
+ expect(line).toContain(`(${process.pid})`);
+ expect(line).toContain("[http]");
+ // No full date in the line.
+ expect(line).not.toMatch(/\d{4}-\d{2}-\d{2}/);
+ });
+
+ it("includes the query string, redacting sensitive params", () => {
+ const line = httpDevFormatter(
+ record({
+ method: "GET",
+ pathname: "/callback",
+ search: "?ref=home&token=%5BREDACTED%5D",
+ status: 200
+ })
+ );
+ expect(line).toContain("/callback?ref=home&token=%5BREDACTED%5D");
});
it("renders the message portion as a morgan dev-style access line — bold method, dimmed duration", () => {
diff --git a/packages/logger/src/http-formatter.ts b/packages/logger/src/http-formatter.ts
index d30b70f006..a92c1038e6 100644
--- a/packages/logger/src/http-formatter.ts
+++ b/packages/logger/src/http-formatter.ts
@@ -13,17 +13,40 @@ function statusColor(status: number): string {
return RESET;
}
+/** Per-level color for the `LEVEL` field. */
+const LEVEL_COLOR: Record<string, string> = {
+ trace: "\x1b[90m",
+ debug: "\x1b[36m",
+ info: "\x1b[32m",
+ warning: "\x1b[33m",
+ error: "\x1b[31m",
+ fatal: "\x1b[35m"
+};
+
+/** Time-only `HH:MM:SS.mmm` from an epoch-ms timestamp (no date). */
+function clockTime(ts: number): string {
+ const d = new Date(ts);
+ const pad = (n: number, width = 2) => String(n).padStart(width, "0");
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(
+ d.getSeconds()
+ )}.${pad(d.getMilliseconds(), 3)}`;
+}
+
+const PID = typeof process !== "undefined" ? process.pid : 0;
+
/**
- * Same timestamp/level/category prefix as the standard `ansiColorFormatter`,
- * but the message portion of an HTTP access-log record (set by
- * `requestIdMiddleware`) renders Morgan "dev"-style: `GET /dashboard 200
- * 12.3 ms`, with the status colored by range. Any `carbon.http` record that
- * isn't a recognized access log (e.g. a manual `getLogger("http")` call)
- * falls back to the normally-rendered message.
+ * Dev formatter for the `carbon.http` category. Renders a pino-style prefix —
+ * `[HH:MM:SS.mmm] LEVEL (pid): [module] …` (time only, no date) — then the
+ * message. For access-log records (set by `requestIdMiddleware`) the message
+ * is a Morgan "dev"-style `METHOD /path?query STATUS 12.3 ms` line, status
+ * colored by range, with any captured (already-redacted) request body appended
+ * dimmed underneath. Any other `carbon.http` record falls back to its rendered
+ * message.
*/
export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({
- format({ timestamp, level, category, message, record }) {
- const { method, pathname, status, responseTime, body } = record.properties;
+ format({ message, record }) {
+ const { method, pathname, search, status, responseTime, body } =
+ record.properties;
let line = message;
if (
@@ -31,21 +54,32 @@ export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({
typeof pathname === "string" &&
typeof status === "number"
) {
+ const query = typeof search === "string" ? search : "";
// Truncate (not round) to at most 1 decimal — no padded trailing zero.
const time =
typeof responseTime === "number"
? ` ${DIM}${Math.trunc(responseTime * 10) / 10} ms${RESET}`
: "";
- line = `${BOLD}${method}${RESET} ${pathname} ${statusColor(status)}${status}${RESET}${time}`;
+ line = `${BOLD}${method}${RESET} ${pathname}${query} ${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.
+ // — 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}`;
+ const clock = clockTime(record.timestamp);
+ const levelColor = LEVEL_COLOR[record.level] ?? RESET;
+ const label = record.level.toUpperCase();
+ // Drop the shared `carbon` root so the module reads `[http]`, `[erp.sales]`.
+ const segments =
+ record.category[0] === "carbon"
+ ? record.category.slice(1)
+ : record.category;
+ const module = segments.join(".");
+
+ return `${DIM}[${clock}]${RESET} ${levelColor}${label}${RESET} ${DIM}(${PID})${RESET}: ${DIM}[${module}]${RESET} ${line}`;
}
});
diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.ts
index 871d42fe96..b60af71338 100644
--- a/packages/logger/src/middleware.server.ts
+++ b/packages/logger/src/middleware.server.ts
@@ -29,6 +29,23 @@ function isSensitiveKey(key: string): boolean {
);
}
+/**
+ * Mask sensitive query-param values (`?code=…`, `?token=…`, …) while keeping the
+ * rest of the query string readable. Returns "" for a bodyless query.
+ */
+function redactSearch(search: string): string {
+ if (!search || search === "?") return "";
+ const params = new URLSearchParams(search);
+ let changed = false;
+ for (const key of params.keys()) {
+ if (isSensitiveKey(key)) {
+ params.set(key, REDACTED);
+ changed = true;
+ }
+ }
+ return changed ? `?${params.toString()}` : search;
+}
+
/**
* Recursively mask values whose key matches a sensitive-field pattern (the same
* `DEFAULT_REDACT_FIELDS` LogTape's `redactByField` uses: password/token/secret/
@@ -118,7 +135,7 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (
context.set(requestIdContext, requestId);
const { method } = request;
- const { pathname } = new URL(request.url);
+ const { pathname, search } = new URL(request.url);
const start = performance.now();
// Capture the body only when debug is actually enabled — skips the clone +
@@ -138,6 +155,7 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (
log.debug("{method} {pathname} → {status} in {responseTime}ms", {
method,
pathname,
+ search: redactSearch(search),
status: res.status,
responseTime: performance.now() - start,
...(body === undefined ? {} : { body })
diff --git a/packages/logger/src/middleware.test.ts b/packages/logger/src/middleware.test.ts
index 97753f92a9..133682c02d 100644
--- a/packages/logger/src/middleware.test.ts
+++ b/packages/logger/src/middleware.test.ts
@@ -201,4 +201,25 @@ describe("requestIdMiddleware body logging", () => {
);
expect(httpRecord()?.properties.body).toBeUndefined();
});
+
+ it("captures the query string and redacts sensitive params", async () => {
+ const request = new Request("http://x/callback?ref=home&token=abc123");
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ const search = httpRecord()?.properties.search as string;
+ expect(search).toContain("ref=home");
+ expect(search).toContain("token=%5BREDACTED%5D");
+ expect(search).not.toContain("abc123");
+ });
+
+ it("logs an empty search for a query-less request", async () => {
+ const request = new Request("http://x/dashboard");
+ await requestIdMiddleware(
+ { request, context: makeContext() } as never,
+ async () => new Response("ok")
+ );
+ expect(httpRecord()?.properties.search).toBe("");
+ });
});