Using Logs to Debug an AI-Built App

· 7 min read ·

A man in a green sweater studies a long paper scroll of log lines with one red entry, while a small robot in a detective hat holds a red flag and a magnifying glass, and an hourglass on the desk runs low

A log is a diary your app writes while it runs. When a user says “checkout broke”, the screen shows “Something went wrong” and the log shows why. To use it, find the one request that failed and read every line that request wrote, in order.

That only works if each log line says which request it belongs to. Most AI-written apps log a bare console.log("here") or nothing at all, so the first job is to add three fields: a request ID, the user, and the input that mattered. A fourth, a release or commit ID, proves a bug started with the last deploy; the demo below skips it to stay small. The rest of this post is the hands-on version, with a small app you can run.

Where do my logs live?

Not on your laptop. Once deployed, the platform keeps whatever your code prints to the console, and the clock on that is shorter than most people expect:

WhereWhat you seeHow long it keeps them
Vercel runtime logsEverything your functions print, including console.log1 hour on Hobby, 1 day on Pro, 3 days on Enterprise (Vercel limits)
Supabase LogsAPI, Postgres, Auth, Storage and Edge Function events1 day on Free, 7 on Pro, 28 on Team (Supabase docs)
Netlify function logsInvocations and console.log outputUp to 7 days, depending on plan (Netlify docs)

Checked against each vendor’s docs on 6 December 2026. Plans change, so look again before you rely on a number.

The part that bites: a user emails you at 9am about a failure yesterday, and on a free Vercel or Supabase plan that evidence is already gone. If a bug is reported, open the logs first and copy out the relevant lines before you do anything else. If you need to look further back, set it up before launch, not after. On Vercel, Drains forward logs to an outside service and are available on the Pro and Enterprise plans (Vercel Drains docs, checked 6 December 2026). On any plan, an error tracker such as Sentry keeps errors on its own retention, so check that plan’s limit.

What does a useful log line look like?

Compare these two for the same failure:

here
Error: Cannot read properties of undefined (reading 'percent')
{"level":"error","msg":"checkout failed","requestId":"e7fca689-1f75-40bd-8122-da84451a42d9","message":"Cannot read properties of undefined (reading 'percent')"}

The first tells you something broke. The second can be searched, filtered by level, and tied to one request. One JSON object per line is the habit. Plain sentences are hard to filter; with JSON you can ask for “only errors” or “only this user” and get exactly that, and an AI assistant can read it without guessing.

A small app to practice on

Here is a tiny checkout service with one planted bug. Make a folder, save these three files, and run node server.js. It needs Node 18 or newer and nothing else.

logger.js
const SECRET_KEYS = /authorization|auth|passw|pwd|token|secret|key$|cookie|cred|service_role/i;
const SECRET_TEXT = [
/\b(?:sk|rk)[-_][A-Za-z0-9_-]{8,}/g,
/\bsb_secret_[A-Za-z0-9_-]{8,}/g,
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g,
/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,
/(:\/\/[^\s:\/@]+:)[^\s@]+@/g,
/([?&](?:api[_-]?key|key|token|access_token|secret|password)=)[^&\s]+/gi,
];
function scrub(text) {
return SECRET_TEXT.reduce((s, re) => s.replace(re, (m, p1) => (typeof p1 === 'string' ? p1 + '[redacted]' + (m.endsWith('@') ? '@' : '') : '[redacted]')), text);
}
function redact(value, key = '') {
if (SECRET_KEYS.test(key)) return '[redacted]';
if (typeof value === 'string') return scrub(value);
if (value instanceof Error) {
return { name: value.name, message: scrub(value.message), stack: scrub(value.stack || '') };
}
if (Array.isArray(value)) return value.map((v) => redact(v));
if (value && typeof value === 'object') {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v, k)]));
}
return value;
}
function makeLogger(write = (line) => process.stdout.write(line + '\n'), base = {}) {
const log = (level, msg, fields = {}) =>
write(JSON.stringify({ time: new Date().toISOString(), level, msg: scrub(String(msg)), ...base, ...redact(fields) }));
log.child = (more) => makeLogger(write, { ...base, ...more });
return log;
}
module.exports = { makeLogger };
// checkout.js (this version has the bug)
const coupons = { SAVE10: { percent: 10 } };
function checkout({ userId, cents, coupon }, log) {
log('info', 'checkout started', { userId, cents, coupon });
const percent = coupon ? coupons[coupon].percent : 0;
const charged = Math.round(cents * (100 - percent) / 100);
log('info', 'checkout done', { userId, charged });
return { charged };
}
module.exports = { checkout };
server.js
const http = require('node:http');
const { randomUUID } = require('node:crypto');
const { makeLogger } = require('./logger');
const { checkout } = require('./checkout');
const root = makeLogger();
http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const log = root.child({ requestId: randomUUID() }); // one ID per request
log('info', 'request', { method: req.method, path: url.pathname });
try {
const result = checkout({
userId: url.searchParams.get('user'),
cents: Number(url.searchParams.get('cents')),
coupon: url.searchParams.get('coupon'),
}, log);
res.end(JSON.stringify(result));
} catch (err) {
log('error', 'checkout failed', { message: err.message, stack: err.stack.split('\n').slice(0, 3).join(' | ') });
res.statusCode = 500;
res.end('Something went wrong');
}
}).listen(3111, () => root('info', 'listening', { port: 3111 }));

The three fields are requestId (made once per request, then attached to every line by child), userId, and coupon, the input that turned out to matter. Run four requests against it, one of them with a coupon that does not exist:

Terminal window
node server.js > app.log &
curl "localhost:3111/checkout?user=u1&cents=2000&coupon=SAVE10"
curl "localhost:3111/checkout?user=u2&cents=1500"
curl "localhost:3111/checkout?user=u3&cents=999&coupon=BLACKFRIDAY"
curl "localhost:3111/checkout?user=u4&cents=500&coupon=SAVE10"

Three succeed and one prints Something went wrong. The screen tells you nothing. The log does.

How do I find the one request that failed?

Two commands, using jq, a free tool for reading JSON lines (install steps are on its site). When you are done, stop the server with kill %1 (on Windows, run the server in a second terminal and stop it with Ctrl+C). First, errors only:

Terminal window
jq -c 'select(.level=="error")' app.log
{"level":"error","msg":"checkout failed","requestId":"e7fca689-1f75-40bd-8122-da84451a42d9","message":"Cannot read properties of undefined (reading 'percent')","stack":"TypeError: ... at checkout (checkout.js:5:44) | at Server.<anonymous> (server.js:13:20)"}

(Trimmed, with a timestamp on each real line.) Then copy that requestId and read everything that request wrote:

Terminal window
jq -c --arg id "e7fca689-1f75-40bd-8122-da84451a42d9" 'select(.requestId==$id) | {msg, userId, coupon, message}' app.log
{"msg":"request","userId":null,"coupon":null,"message":null}
{"msg":"checkout started","userId":"u3","coupon":"BLACKFRIDAY","message":null}
{"msg":"checkout failed","userId":null,"coupon":null,"message":"Cannot read properties of undefined (reading 'percent')"}

(The nulls are fields that line did not have.) The story reads top to bottom: user u3 entered a coupon called BLACKFRIDAY, and the code crashed on .percent because that coupon is not in the table. The stack trace alone said “undefined”; the logged coupon said why. If the trace itself looks like noise, here is how to read it. On Vercel or Supabase you do the same thing in the web UI: filter to errors, find the request, read the lines around it.

What should a log never contain?

Passwords, tokens, API keys, card numbers, and full request headers. Logs are copied into dashboards, error trackers and AI chats, so a secret that gets logged gets spread. The leaked keys post lists error trackers and logs as one of the five places keys escape.

The logger above blanks any field whose name looks secret, at any depth. It also scans every string for known secret shapes, anywhere in the string: sk_ and rk_ keys, sb_secret_, JWTs, Bearer tokens, passwords inside connection strings such as postgres://user:pw@host, and api_key= style URL parameters. It logs an Error as name, message and stack, scrubbed, because JSON.stringify turns an Error into {}.

Two earlier versions failed tests. The first only checked top-level field names and leaked headers.authorization, stripeKey and credentials. The second only matched secrets at the start of a string. In a scratch run it logged a mid-sentence sk_live_..., a URL ?api_key= and a connection-string password in full, and logged an Error as {}.

Limits remain. Secrets in other formats go through, and names ending in key are blanked. The logger does not blank sessionId by name; if your session ID is a credential, do not log it. For anything past a demo, use a logger with built-in redaction, such as pino’s redact option.

Test cases for your logging

Logs are behavior too. Save this as test/logs.test.js and run node --test. Each test says something you want to be true of the logs, not how they are built.

const test = require('node:test');
const assert = require('node:assert');
const { makeLogger } = require('../logger');
const { checkout } = require('../checkout');
function capture() {
const lines = [];
const log = makeLogger((line) => lines.push(JSON.parse(line)));
return { lines, log };
}
test('every line from one request carries the same requestId', () => {
const { lines, log } = capture();
checkout({ userId: 'u1', cents: 2000, coupon: 'SAVE10' }, log.child({ requestId: 'r-1' }));
assert.ok(lines.length >= 2);
assert.ok(lines.every((l) => l.requestId === 'r-1'));
});
test('secrets never reach the logs', () => {
const lines = [];
const log = makeLogger((line) => lines.push(line));
log('info', 'login', { userId: 'u1', authorization: 'Bearer abc123', apiKey: 'sk_live_xyz' });
const text = lines.join('\n');
assert.ok(!text.includes('abc123'));
assert.ok(!text.includes('sk_live_xyz'));
assert.ok(text.includes('u1'));
});
test('secrets nested in headers, under other names, or inside values never reach the logs', () => {
const lines = [];
const log = makeLogger((line) => lines.push(line));
log('info', 'request', {
userId: 'u1',
headers: { authorization: 'Bearer abc123', cookie: 'sid=cookie999' },
stripeKey: 'sk_live_xyz',
note: 'sk_live_inside_value',
credentials: { user: 'u1', pw: 'hunter2' },
});
const text = lines.join('\n');
for (const secret of ['abc123', 'cookie999', 'sk_live_xyz', 'sk_live_inside_value', 'hunter2']) {
assert.ok(!text.includes(secret), `leaked: ${secret}`);
}
assert.ok(text.includes('u1'));
});
function logText(fields) {
const lines = [];
const log = makeLogger((line) => lines.push(line));
log('info', 'event', fields);
return lines.join('\n');
}
test('secrets in the middle of a string never reach the logs', () => {
const text = logText({
userId: 'u1',
message: 'charge failed for sk_live_MIDSTRING1234 on retry',
url: 'https://api.example.com/v1/items?api_key=URLKEY9999&page=2',
db: 'could not connect to postgres://app:[email protected]:5432/shop',
header: 'Authorization: Bearer MIDBEARER5555',
});
for (const secret of ['MIDSTRING1234', 'URLKEY9999', 'DBPASS7777', 'MIDBEARER5555']) {
assert.ok(!text.includes(secret), `leaked: ${secret}`);
}
assert.ok(text.includes('u1'));
assert.ok(text.includes('page=2'), 'harmless parts of the string must survive');
assert.ok(text.includes('db.example.com'), 'the host is the useful part of a connection error');
});
test('an Error passed as a field keeps its message, minus secrets', () => {
const text = logText({ err: new Error('connect failed: postgres://app:ERRPASS8888@db:5432/shop') });
assert.ok(text.includes('connect failed'), 'the error message must be logged');
assert.ok(!text.includes('ERRPASS8888'));
});
test('harmless fields with secret-looking names are kept', () => {
const text = logText({ keyword: 'shoes', sessionId: 's-123', keyId: 'k-42' });
assert.ok(text.includes('shoes'));
assert.ok(text.includes('s-123'));
assert.ok(text.includes('k-42'));
});
test('scrubbed strings keep their shape: [redacted] replaces only the secret', () => {
const lines = [];
const log = makeLogger((line) => lines.push(JSON.parse(line)));
log('info', 'event', {
note: 'key is sb_secret_ABCDEFGHIJ and Bearer abc.def.ghi here',
db: 'postgres://app:[email protected]/shop',
url: 'https://x.test/a?api_key=URLKEY9999&page=2',
});
assert.strictEqual(lines[0].note, 'key is [redacted] and [redacted] here');
assert.strictEqual(lines[0].db, 'postgres://app:[redacted]@db.example.com/shop');
assert.strictEqual(lines[0].url, 'https://x.test/a?api_key=[redacted]&page=2');
});
test('an unknown coupon is rejected with a clear message', () => {
const { log } = capture();
assert.throws(
() => checkout({ userId: 'u3', cents: 999, coupon: 'BLACKFRIDAY' }, log),
/unknown coupon: BLACKFRIDAY/i
);
});
test('a rejected coupon is logged as a warning with the coupon and user', () => {
const { lines, log } = capture();
try { checkout({ userId: 'u3', cents: 999, coupon: 'BLACKFRIDAY' }, log); } catch {}
const warn = lines.find((l) => l.level === 'warn');
assert.ok(warn, 'expected a warn line');
assert.strictEqual(warn.coupon, 'BLACKFRIDAY');
assert.strictEqual(warn.userId, 'u3');
});

Against the buggy checkout.js, the request ID test and every logger test pass and the two coupon tests fail, which is the bug reproduced as a test:

✔ every line from one request carries the same requestId
✔ secrets never reach the logs
✔ secrets nested in headers, under other names, or inside values never reach the logs
✔ secrets in the middle of a string never reach the logs
✔ an Error passed as a field keeps its message, minus secrets
✔ harmless fields with secret-looking names are kept
✔ scrubbed strings keep their shape: [redacted] replaces only the secret
✖ an unknown coupon is rejected with a clear message
✖ a rejected coupon is logged as a warning with the coupon and user
ℹ pass 7
ℹ fail 2

Now fix the coupon handling. Replace the whole of checkout.js below the coupons line with:

function checkout({ userId, cents, coupon }, log) {
log('info', 'checkout started', { userId, cents, coupon });
const found = coupon ? coupons[coupon] : null;
if (coupon && !found) {
log('warn', 'unknown coupon', { userId, coupon });
throw new Error(`Unknown coupon: ${coupon}`);
}
const percent = found ? found.percent : 0;
const charged = Math.round(cents * (100 - percent) / 100);
log('info', 'checkout done', { userId, charged });
return { charged };
}
module.exports = { checkout };
✔ every line from one request carries the same requestId
✔ secrets never reach the logs
✔ secrets nested in headers, under other names, or inside values never reach the logs
✔ secrets in the middle of a string never reach the logs
✔ an Error passed as a field keeps its message, minus secrets
✔ harmless fields with secret-looking names are kept
✔ scrubbed strings keep their shape: [redacted] replaces only the secret
✔ an unknown coupon is rejected with a clear message
✔ a rejected coupon is logged as a warning with the coupon and user
ℹ pass 9
ℹ fail 0

The tests describe what a person debugging at 2am needs: lines they can group, no secrets, and the input that mattered. If an AI later rewrites logger.js and drops the redaction, five tests go red (checked in a scratch run: with redaction removed, 4 pass and 5 fail). They also only cover what they name. Nothing here checks that logs are kept long enough, or that a secret in an unknown format is caught.

What do I paste into my AI tool?

To add logging to an existing app:

Add structured logging to this app. One JSON object per line with time, level, msg. Create a request ID for every incoming request and attach it to every log line for that request. Log the user ID and the inputs that decide what the code does. Never log passwords, tokens, API keys, request headers or bodies. Do not change any behavior. Write tests that prove the request ID is on every line and that secrets are redacted.

To debug a failure, paste the lines for one request (the jq output above), not the whole log file, and add:

These are all the log lines from one failed request. Do not change code yet. Tell me what happened in order, which line shows the first thing that went wrong, and what input caused it.

For what to do when the AI’s fix does not hold, see Stop pasting the error back, and Your AI fixed one bug and broke two for the tests that catch the next break.

The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.

Comments