research/logging-what-an-automated-job-did
Logging What an Automated Job Did: One JSON Line per Item and a Run ID, Tested in Node.js
Engineering Note · December 1, 2026 · 8 minute read · Node.js · Scheduled Jobs · Logging · Reliability
Give every run of a scheduled job an ID, and write one JSON line for each item it touches, plus a line when the run starts and a line when it ends. With that in place, one jq command answers “what happened to this customer?” across every run, and another lists runs that started but never finished, which is how a crash looks in the log. How you write the lines matters as much as what is in them. In our tests, fs.appendFileSync kept every line through a thrown error, process.exit() and kill -9. A write stream lost the last two lines, the failure and the end of the run, when the job called process.exit().
Everything below was run on Linux 6.18 (ext4) with Node.js 22.23.5 and jq 1.7. The outputs are real.
Why does a job need its own log?
A small business’s automated jobs are usually quiet: a nightly reminder email, a sync from the booking system into a spreadsheet, an invoice run. They are quiet until a customer says “I got that reminder twice” or “I never got my invoice.” Then someone needs to answer two questions quickly. What did the job do for this customer, and did every run finish?
A job that prints “done, sent 37” can’t answer either. A job that logs one structured line per item can, and it takes about ten lines of code. It also pairs with the safeguards in our notes on stopping a scheduled job from running twice and heartbeat checks for scheduled jobs: those stop overlaps and catch missing runs, and the log shows what each run actually did.
What goes in each line?
Our test job sends a reminder for every booking not yet reminded. It writes a run_start line, an item line per booking and a run_end line with totals. Every line carries the same run ID, made from the start time plus six random hex characters, so it sorts by time and two runs started in the same second still differ:
const runId = process.env.RUN_ID || `${new Date().toISOString().slice(0,19).replace(/[-:]/g,'')}-${crypto.randomBytes(3).toString('hex')}`;
function log(event, fields = {}) {
fs.appendFileSync(LOG, JSON.stringify({ ts: new Date().toISOString(), run: runId, event, ...fields }) + '\n');
}
log('run_start', { due: due.length, pid: process.pid });
for (const b of due) {
const t0 = Date.now();
try {
await send(b);
b.reminded = true;
fs.writeFileSync(DB, JSON.stringify(bookings));
counts.sent++;
log('item', { booking: b.id, to: b.email, outcome: 'sent', ms: Date.now() - t0 });
} catch (e) {
counts.failed++;
log('item', { booking: b.id, to: b.email, outcome: 'failed', error: e.message, ms: Date.now() - t0 });
}
}
log('run_end', counts);
Two choices are deliberate. The item line is written after the work, so a line that says “sent” means the send returned. And a failure on one item is logged and the loop moves on, so one bad address does not stop the other reminders.
We seeded five bookings and made booking 103 throw on the first run. The log:
{"ts":"2026-11-30T20:03:48.474Z","run":"20261130T200348-ade2d8","event":"run_start","due":5,"pid":1099}
{"ts":"2026-11-30T20:03:48.525Z","run":"20261130T200348-ade2d8","event":"item","booking":101,"to":"customer1@example.com","outcome":"sent","ms":50}
{"ts":"2026-11-30T20:03:48.576Z","run":"20261130T200348-ade2d8","event":"item","booking":102,"to":"customer2@example.com","outcome":"sent","ms":51}
{"ts":"2026-11-30T20:03:48.626Z","run":"20261130T200348-ade2d8","event":"item","booking":103,"to":"customer3@example.com","outcome":"failed","error":"mailbox unavailable (550)","ms":50}
{"ts":"2026-11-30T20:03:48.678Z","run":"20261130T200348-ade2d8","event":"item","booking":104,"to":"customer4@example.com","outcome":"sent","ms":51}
{"ts":"2026-11-30T20:03:48.729Z","run":"20261130T200348-ade2d8","event":"item","booking":105,"to":"customer5@example.com","outcome":"sent","ms":51}
{"ts":"2026-11-30T20:03:48.729Z","run":"20261130T200348-ade2d8","event":"run_end","sent":4,"failed":1}
A second run picked up only the failed booking, because it was never marked as reminded:
run 20261130T200348-8145dd: sent 1, failed 0
How do you answer “what happened to this customer?”
Filter on the address. jq reads one JSON value per line, so it needs nothing special for this format:
$ jq -c 'select(.to == "customer3@example.com") | {ts, run, outcome, error}' job.jsonl
{"ts":"2026-11-30T20:03:48.626Z","run":"20261130T200348-ade2d8","outcome":"failed","error":"mailbox unavailable (550)"}
{"ts":"2026-11-30T20:03:48.819Z","run":"20261130T200348-8145dd","outcome":"sent","error":null}
The first run failed for this customer with a 550 from the mail server, and the next run sent it about 200 ms later. (jq prints null for a field the line does not have.) In a real job the runs would be hours apart, and the answer to the customer is now precise: the reminder failed at one time and went out at another.
How do you find a run that crashed?
A run that dies does not write its run_end line. We reset the bookings, started the job, and killed it with kill -9 about 170 ms in. Then we grouped the log by run ID and kept runs with no end line:
$ jq -rs 'group_by(.run)[] | select(any(.event=="run_end")|not) | "\(.[0].run) started \(.[0].ts), \(map(select(.event=="item"))|length) items logged, last: \(.[-1].booking // "none")"' job.jsonl
20261130T200353-4927f0 started 2026-11-30T20:03:53.917Z, 2 items logged, last: 102
The killed run had handled bookings 101 and 102. The next run will start from 103, because those two were saved as reminded right after each send. This is the same “record each item as done” fix that our lock-file note found a lock cannot give you on its own.
The -s flag reads the whole file into memory. That is fine for a log rotated daily or weekly. For a large log, filter by date first.
Do log lines survive a crash?
This is where the method of writing matters. We wrote a test job that logs 20 “sent” lines as it goes, then hits a fatal error, logs the failure and the end of the run, and calls process.exit(1), as a top-level error handler often does:
const log = o => { const l = JSON.stringify(o) + '\n'; stream ? stream.write(l) : fs.appendFileSync(FILE, l); };
for (let i = 1; i <= 20; i++) { await sleep(5); log({ event: 'item', n: i, outcome: 'sent' }); }
log({ event: 'item', n: 21, outcome: 'failed', error: 'payment API returned 500' });
log({ event: 'run_end', fatal: true });
process.exit(1);
Real output:
appendFileSync: 22 lines; last: {"event":"run_end","fatal":true}
stream: 20 lines; last: {"event":"item","n":20,"outcome":"sent"}
The stream version lost exactly the two lines anyone would need: the error and the fact that the run ended. The Node.js documentation warns that process.exit() forces the process to exit “even if there are still asynchronous operations pending that have not yet completed fully.” A write stream queues writes and performs them later, so whatever is still in its queue is dropped.
We then pushed it further: 1,000 lines written in a tight loop, followed by four different endings.
appendFileSync, normal: 1000 of 1000 lines
appendFileSync, throw: 1000 of 1000 lines
appendFileSync, exit: 1000 of 1000 lines
appendFileSync, kill: 1000 of 1000 lines
stream, normal: 1000 of 1000 lines
stream, throw: 0 of 1000 lines
stream, exit: 0 of 1000 lines
stream, kill: 0 of 1000 lines
With the stream, an uncaught exception, process.exit() or kill -9 straight after the loop left no file at all, because even opening the file is asynchronous and had not happened yet. appendFileSync finished each write before returning, so every line was in the file, including after kill -9, which no code can intercept.
The cost of appendFileSync is one open, write and close per line, and the event loop waits for each. For a job that sends a few hundred emails, each taking tens of milliseconds, that is noise. For a server logging thousands of requests a second, it would not be the right tool, and a logging library with a proper flush on shutdown is worth the dependency.
Note that “in the file” means handed to the operating system. A power cut can still lose the last writes; we did not test that.
Can two runs append to the same file?
If two runs overlap, or several jobs share one log, their lines land in the same file. We started four processes at once, each appending 2,000 lines (300 for the largest size) with appendFileSync, which opens the file with the 'a' flag, then parsed every line:
line size ~200 bytes: 8000 lines, 0 unparseable
line size ~8000 bytes: 8000 lines, 0 unparseable
line size ~100000 bytes: 1200 lines, 0 unparseable
No line was split or interleaved, even at 100 KB. That is what we saw on one Linux machine with a local ext4 disk. We would not count on it on a network file system, and the run ID is what lets you separate overlapping runs anyway. If in doubt, write one file per run, named after the run ID.
What should you leave out of the lines?
A log is copied, shared and kept for longer than anyone plans. Log identifiers that let you find the record (a booking ID, an invoice number) and keep personal details to what you need to answer a complaint. Our test logs the email address because the complaint usually arrives by email; a job that handles payments should log the payment provider’s reference, never card details. Decide how long the files are kept and delete them on a schedule, the same way you would expire old rows in a database.
Limitations
- Everything ran on one Linux machine with a local ext4 disk. Appends from several processes on network file systems, macOS or Windows may behave differently, and we did not test them.
- We tested process endings (
throw,process.exit(),kill -9), not a power cut or a full disk. After a power cut, lines the operating system had not yet written to disk can be lost even withappendFileSync. - The concurrency test is four processes on one machine, for three line sizes. It shows what happened here, not a guarantee.
- We compared
appendFileSyncwith a plainfs.createWriteStream. Logging libraries have their own flush and shutdown behavior, which we did not test. jq -sreads the whole log into memory. It is fine for a daily or weekly file and not for a very large one.
Sources
- Node.js 22 documentation: Process (
process.exit()and pending asynchronous operations) - Node.js 22 documentation: File system (
fs.appendFileSync,fs.createWriteStreamand the'a'flag)
Related reading
- A Dry-Run Mode for a Script That Changes Data: Printing the Plan Before Applying It
- Stopping a Scheduled Job From Running Twice: A Lock File, a PID Check and flock, Tested in Node.js
- Heartbeat Checks for Scheduled Jobs: Alerting When a Job Did Not Run
Frequently asked questions
What should a scheduled job log?
One line when the run starts, one line for each item it handles, and one line when it ends. Each line should carry a timestamp, a run ID shared by the whole run, the item's ID, the outcome and any error message. That is enough to answer what happened to a given customer and whether a run finished.
Why log JSON lines instead of plain text?
Each line is a complete record that tools such as jq can filter without fragile text parsing. You can ask for every line about one customer, or every run that has a start line but no end line, in a single command. Plain text works until someone needs to answer a question the format did not expect.
What is a run ID for?
It ties together every line a single run wrote. When two runs overlap or a run is retried, the run ID shows which attempt sent an email or failed on an item. In our test it let one command list the runs that started and never wrote an end line, which is how a crashed run shows up.
Can log lines be lost if a Node.js job crashes?
Yes, depending on how they are written. In our test, a job that logged through fs.createWriteStream and then called process.exit() lost its last two lines, which were the error and the end of the run. The same job using fs.appendFileSync kept every line, even when killed with kill -9.
Can several processes append to the same log file safely?
In our test on Linux with ext4, four Node.js processes appending with fs.appendFileSync produced no broken lines, with lines of about 200 bytes, 8 KB and 100 KB. We did not test network file systems, Windows or macOS, where the result can differ. Giving each run its own file avoids the question.