Logging an entire AI request or provider response makes every newly added field part of your logging policy. A safer default for operational telemetry is to construct a fresh record containing only approved metadata. This tutorial retains a request identifier, completion state and elapsed time while excluding synthetic prompt, answer and authorization-like fields.

The example is an AI adapter logging boundary. It starts with a plain event object that an adapter might produce after a request completes. No provider is contacted, and every content marker in the tests is synthetic.

Prerequisites

Use a maintained Node.js installation with ES module support. The example was executed on Node.js 26.13.0 and uses built-in assertions only. Save it as ai-log.mjs. The logging function itself uses ordinary JavaScript and expects a plain application event.

Complete example

import assert from 'node:assert/strict';

function auditLine(event) {
  if (!['completed', 'failed'].includes(event.state)) throw new Error('bad state');
  if (typeof event.requestId !== 'string' || !/^r-[0-9]{1,8}$/.test(event.requestId)) throw new Error('bad id');
  if (!Number.isSafeInteger(event.elapsedMs) || event.elapsedMs < 0) throw new Error('bad time');
  // Construct a new record. Never spread the raw provider event here.
  return JSON.stringify({
    requestId: event.requestId,
    state: event.state,
    elapsedMs: event.elapsedMs
  });
}
const event = {
  requestId: 'r-12', state: 'completed', elapsedMs: 42,
  prompt: 'SYNTHETIC_PROMPT', answer: 'SYNTHETIC_ANSWER',
  provider: {headers: {authorization: 'SYNTHETIC_SECRET'}}
};
const line = auditLine(event);
assert.deepEqual(JSON.parse(line), {requestId: 'r-12', state: 'completed', elapsedMs: 42});
for (const marker of ['SYNTHETIC_PROMPT', 'SYNTHETIC_ANSWER', 'SYNTHETIC_SECRET']) {
  assert.equal(line.includes(marker), false);
}
const circular = {...event}; circular.raw = circular;
assert.equal(auditLine(circular), line);
for (const patch of [{requestId: '[email protected]'}, {state: 'other'}, {elapsedMs: NaN}]) {
  assert.throws(() => auditLine({...event, ...patch}));
}
console.log(line);
console.log('allowlist fixtures passed; no provider called');

Run and expected output

node ai-log.mjs
{"requestId":"r-12","state":"completed","elapsedMs":42}
allowlist fixtures passed; no provider called

How the boundary works

The new object has exactly three properties. Unknown top-level fields and arbitrary nested provider data never enter it. This also means an unrelated circular reference in the original event cannot break serialization of the approved record.

Each permitted value has its own contract. The identifier must be a short application-generated string matching the demonstrated format. State must belong to a closed vocabulary. Elapsed time must be a nonnegative safe integer, preventing NaN or an accidental fractional duration from reaching the record.

The round-trip assertion checks the complete output shape. Separate marker checks make the intended exclusions visible to a reviewer. Both are useful: a test that searches only for one secret string could miss a newly leaked field with different contents.

Edge cases and troubleshooting

Generate request identifiers independently of user content. A format restriction alone does not make an identifier anonymous. Do not repurpose an email address, account number or prompt fragment as a correlation ID. Decide retention and access rules for operational metadata separately.

Adding an approved field requires a deliberate validation rule and an updated exact-shape test. Avoid replacing the fresh object with a spread of the original event followed by deletions; that approach depends on remembering every field that should be removed.

This function assumes ordinary application data. It does not neutralize hostile JavaScript getters, proxies or a compromised runtime. It also cannot protect a different log statement that serializes the original provider error. Route adjacent error reporting through similarly reviewed records. These fixture checks validate the record construction, not a production logging backend or its retention configuration.

References and related tutorials

See MDN’s JSON.stringify reference for serialization behavior. Browse Javascript tutorials and AI tutorials.