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.

(improvement): dev server logs show the real error and its details (#1713)

Anshul sharmab79505775cc8
diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
index 4addaa6308..86a99811e5 100644
--- a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
@@ -160,8 +160,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
} catch (err) {
logger.error("Paperless Parts webhook failed", {
companyId,
- error: err instanceof Error ? err.message : String(err),
- stack: err instanceof Error ? err.stack : undefined
+ error: err
});
return data({ success: false }, { status: 500 });
}
diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsx
index 2d84583e93..1dac48fe49 100644
--- a/apps/erp/app/routes/x+/settings+/company.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx
@@ -124,7 +124,6 @@ export async function action({ request }: ActionFunctionArgs) {
if (error instanceof Response) throw error;
logger.error("Company create failed: {message}", {
message: error instanceof Error ? error.message : String(error),
- stack: error instanceof Error ? error.stack : undefined,
error
});
throw error;
diff --git a/packages/ee/src/mcp/types.ts b/packages/ee/src/mcp/types.ts
index 074229fdee..f4224cb9d3 100644
--- a/packages/ee/src/mcp/types.ts
+++ b/packages/ee/src/mcp/types.ts
@@ -84,8 +84,7 @@ export function withErrorHandling<T extends Record<string, unknown>>(
} catch (error) {
logger.error("Error in handler", {
fallbackMessage,
- error,
- stack: error instanceof Error ? error.stack : "No stack"
+ error
});
return {
content: [
diff --git a/packages/logger/src/config.server.ts b/packages/logger/src/config.server.ts
index 4667dfc734..3b6d554140 100644
--- a/packages/logger/src/config.server.ts
+++ b/packages/logger/src/config.server.ts
@@ -1,11 +1,11 @@
import { AsyncLocalStorage } from "node:async_hooks";
import {
- ansiColorFormatter,
configureSync,
getConsoleSink,
getJsonLinesFormatter
} from "@logtape/logtape";
import { redactByField } from "@logtape/redaction";
+import { devFormatter } from "./dev-formatter";
import { readEnv } from "./env";
import { httpDevFormatter } from "./http-formatter";
import { type CarbonLogLevel, resolveLevel } from "./levels";
@@ -24,7 +24,7 @@ export type ConfigureLoggingOptions = {
/**
* Configure LogTape for a Node server once per process.
*
- * - dev → `ansiColorFormatter` (colored terminal)
+ * - dev → `devFormatter` (colored terminal)
* - prod → `getJsonLinesFormatter()` (JSONL, no ANSI), field-redacted
*
* Idempotent: a `globalThis` flag survives Vite SSR module re-evaluation, and
@@ -40,7 +40,7 @@ export function ensureLoggingConfigured(
const level = options.level ?? resolveLevel("server");
const pretty = options.pretty ?? !isProd;
- const formatter = pretty ? ansiColorFormatter : getJsonLinesFormatter();
+ const formatter = pretty ? devFormatter : getJsonLinesFormatter();
const consoleSink = getConsoleSink({ formatter });
// Redact sensitive field names (password, token, secret, …) before records
// reach the sink. Cheap: matches field names, not values. Masks rather than
diff --git a/packages/logger/src/dev-formatter.test.ts b/packages/logger/src/dev-formatter.test.ts
new file mode 100644
index 0000000000..b5ad2b79d3
--- /dev/null
+++ b/packages/logger/src/dev-formatter.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from "vitest";
+import { devFormatter } from "./dev-formatter";
+
+function record(rawMessage: string, properties: Record<string, unknown>) {
+ return {
+ category: ["carbon", "auth"],
+ level: "error",
+ message: [rawMessage],
+ rawMessage,
+ timestamp: Date.now(),
+ properties
+ } as never;
+}
+
+// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping ANSI colors
+const plain = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
+
+describe("devFormatter", () => {
+ it("appends an error the message doesn't reference, with its stack", () => {
+ const error = new TypeError("Cannot read properties of undefined");
+ const line = plain(
+ devFormatter(record("Failed to finalize quote", { error }))
+ );
+ expect(line).toContain("Failed to finalize quote");
+ expect(line).toContain("TypeError: Cannot read properties of undefined");
+ expect(line).toContain("dev-formatter.test.ts");
+ });
+
+ it("does not repeat properties the message already renders", () => {
+ const line = plain(
+ devFormatter(record("Loaded {count} rows", { count: 3 }))
+ );
+ expect(line).not.toContain("{ count");
+ });
+
+ it("appends only the unreferenced properties", () => {
+ const line = plain(
+ devFormatter(record("Loaded {count} rows", { count: 3, quoteId: "q1" }))
+ );
+ expect(line).toContain("quoteId: 'q1'");
+ expect(line).not.toContain("count: 3");
+ });
+
+ it("treats escaped braces as literal text, not placeholders", () => {
+ const line = plain(
+ devFormatter(record("Literal {{code}} here", { code: "x1" }))
+ );
+ expect(line).toContain("code: 'x1'");
+ });
+
+ it("skips the ambient requestId and ends with one newline", () => {
+ const line = devFormatter(record("Hello", { requestId: "r1" }));
+ expect(plain(line)).not.toContain("r1");
+ expect(line.endsWith("\n")).toBe(true);
+ expect(line.endsWith("\n\n")).toBe(false);
+ });
+});
+
+describe("devFormatter fallbacks", () => {
+ it("prints the plain line when properties are missing", () => {
+ const line = devFormatter({
+ ...(record("Hello", {}) as object),
+ properties: undefined
+ } as never);
+ expect(plain(line)).toContain("Hello");
+ });
+
+ it("prints the plain line when reading a property throws", () => {
+ const properties = {
+ get broken() {
+ throw new Error("boom");
+ }
+ };
+ const line = devFormatter({
+ ...(record("Hello", {}) as object),
+ properties
+ } as never);
+ expect(plain(line)).toContain("Hello");
+ expect(line.endsWith("\n")).toBe(true);
+ });
+});
diff --git a/packages/logger/src/dev-formatter.ts b/packages/logger/src/dev-formatter.ts
new file mode 100644
index 0000000000..6416c33be9
--- /dev/null
+++ b/packages/logger/src/dev-formatter.ts
@@ -0,0 +1,43 @@
+import { inspect } from "node:util";
+import {
+ ansiColorFormatter,
+ type LogRecord,
+ type TextFormatter
+} from "@logtape/logtape";
+
+// On every in-request record; useful in prod JSON, noise on each dev line.
+const AMBIENT_KEYS = new Set(["requestId"]);
+
+// Returns null for `{*}`, which already renders every property.
+function referencedKeys(raw: LogRecord["rawMessage"]): Set<string> | null {
+ if (typeof raw !== "string") return new Set();
+ const keys = new Set<string>();
+ // `{{` / `}}` are escaped braces, not placeholders.
+ for (const [, key = ""] of raw.matchAll(/(?<!\{)\{([^{}]+)\}(?!\})/g)) {
+ const name = key.trim();
+ if (name === "*") return null;
+ keys.add(name.split(/[.[]/)[0] ?? name);
+ }
+ return keys;
+}
+
+// `ansiColorFormatter` drops properties the message doesn't reference (e.g. `{ error }`).
+export const devFormatter: TextFormatter = (record) => {
+ const line = ansiColorFormatter(record);
+ try {
+ const referenced = referencedKeys(record.rawMessage);
+ if (referenced === null) return line;
+
+ const extra = Object.fromEntries(
+ Object.entries(record.properties ?? {}).filter(
+ ([key]) => !referenced.has(key) && !AMBIENT_KEYS.has(key)
+ )
+ );
+ if (Object.keys(extra).length === 0) return line;
+
+ return `${line.trimEnd()} ${inspect(extra, { colors: true, depth: 5 })}\n`;
+ } catch {
+ // Appending details must never cost the log line itself.
+ return line;
+ }
+};