Why your log's caller location always points at one line

Some bugs hide. This one stood in every log line for weeks, and I still walked past it: my logger’s caller location always pointed at one line, and that line was not in anyone’s app.
My logger has an optional feature called captureCaller. When it is on, every server-side log line carries the place it came from:
INFO order created caller: "app/checkout/actions.ts:42"That little caller field is the whole point. A log that says what happened is useful. A log that also says where in your code it happened saves you a grep.
Mine said this instead, on every single line:
caller: "src/utils/caller.ts:37"Not sometimes. Always. A route handler, a Server Action, a background job — same file, same line, every time. Line 37 is not in anyone’s app. Line 37 was inside my own logger.
How the feature is supposed to work
There is no magic available here. JavaScript has no built-in “who called me”. The only way to find out is to create an error you never intend to throw, read its stack trace, and look at the lines. (An Error is a strange little object in general — it is also why JSON.stringify(error) prints an empty object in your logs.)
A stack trace is just a list of the function calls that got you here, newest first. When your app calls log.info(), the top of that list is not your code. It is the logger’s own code — the function that captured the stack, the function that called it, and so on. Your actual call site is a few rows down.
So the job is: walk the list from the top, skip the frames that belong to the library, and return the first one that doesn’t. That first non-library frame is the caller.
Everything rests on the word skip.
The bug: the filter forgot about itself
The original skip rule was a hardcoded list of path fragments. Roughly:
const LIBRARY_FRAGMENTS = ['/core/', '/logger/']
// skip any stack line containing one of those, return the first survivorThe idea reads fine. The problem is the file doing the skipping. It lived at src/utils/caller.ts, and src/utils/caller.ts contains neither /core/ nor /logger/.
So the walk started at the top of the stack, looked at the very first frame — which is always this file, because this file is where new Error() runs — asked “is this library code?”, and the list said no.
First frame examined. First frame returned. Every time. The answer was always the location of the new Error() call itself.
A feature designed to tell you where a log came from could only ever tell you where it was born.
See it yourself in two small files
You do not need my library to watch this happen. Two files and Node is enough. Put them in an empty folder.
lib/caller.mjs — this plays the part of the logger:
const OLD_FRAGMENTS = ['/core/', '/logger/'] // the buggy skip list
const SELF_PATH = decodeURIComponent(import.meta.url.slice('file://'.length))
function frames() {
const stack = new Error().stack
return stack.split('\n').slice(1) // drop the "Error" header
}
const loc = (line) =>
(line.match(/\(([^)]+)\)\s*$/) ?? line.match(/at\s+(.+)$/))?.[1]?.trim()
export function callerOld() {
for (const line of frames()) {
if (OLD_FRAGMENTS.some((f) => line.includes(f))) continue
const found = loc(line)
if (found && !found.startsWith('node:')) return found
}
}
export function callerNew() {
for (const line of frames()) {
if (line.includes(SELF_PATH)) continue
const found = loc(line)
if (found && !found.startsWith('node:')) return found
}
}app/page.mjs — this plays the part of your app:
import { callerOld, callerNew } from '../lib/caller.mjs'
console.log('old filter ->', callerOld())
console.log('new filter ->', callerNew())Run node app/page.mjs. I tested this on Node 22.16.0 and got:
old filter -> file:///.../demo/lib/caller.mjs:7:17
new filter -> file:///.../demo/app/page.mjs:4:28Line 7 of lib/caller.mjs is the new Error() line. The old filter points at the library. The new one points at the file that actually asked.
Both functions read the same stack. The only difference is what counts as “mine”.
Why nobody noticed for so long
A feature that is completely broken can be more invisible than one that is slightly broken, which sounds backwards until you look at the output.
caller: "src/utils/caller.ts:37" is a well-formed string. It is not undefined, not empty, nothing threw. A field was asked for and a field appeared. Your eye reads “the feature works” and moves on.
It only falls apart when you put two log lines from two unrelated parts of the app side by side and notice they claim to come from the same place. Most of us read logs one line at a time, especially when we are chasing something else. So the bug sat there, printing a confident constant, while quietly paying the cost of capturing a stack trace on every log call for a value nobody could use.
The second problem: the list was already doomed
Even if I had added /utils/caller to that list, it would have broken again the moment anyone installed the package.
Those fragments describe where the files sit in my repository, during development. Once a package is published and a bundler gets hold of it, the library does not live in a folder called core anymore. It lives somewhere like:
node_modules/@developerehsan/nextjs-logger/dist/chunk-4f2a91.jsOne generated file, with a hash in the name, containing all of it. None of the original fragments match that. The skip list was built around one temporary shape of the world, and it would stop matching the moment the shape changed — silently, with no error, exactly like the first bug.
That is the real lesson hiding in here, and it is not about stack traces.
The fix: stop guessing where you are, ask
The fix is not a longer list. It is one fact the module can look up about itself at runtime:
const SELF_PATH = (() => {
try {
const url = import.meta.url
if (!url?.startsWith('file://')) return ''
return decodeURIComponent(url.slice('file://'.length))
} catch {
return ''
}
})()import.meta.url is the module’s own address, as it actually exists right now. Not where I assume it is. Not where it was when I wrote the code. Where it is.
From that single true fact everything else can be derived. The file’s own path goes into the skip list first, which kills the original bug by construction — it is not a guess that could be wrong, it is the file saying “me”. Then the surrounding folders give you the rest:
const LIB_SUBDIRS = ['core', 'queue', 'transport', 'utils', 'provider', 'relay', 'security']
const LIB_FRAME_MARKERS = (() => {
if (!SELF_PATH) return []
const selfDir = dirname(SELF_PATH)
const parentDir = dirname(selfDir)
const markers = [SELF_PATH]
for (const base of [selfDir, parentDir]) {
if (!base) continue
for (const sub of LIB_SUBDIRS) markers.push(`${base}/${sub}/`)
}
return markers
})()Anchoring to both the file’s folder and its parent covers the layouts the package can ship in. From src/utils/caller.ts you get markers like .../src/core/. From dist/caller.js you get .../dist/core/. And in the fully bundled case, where every piece of the library has been merged into one file, SELF_PATH on its own already covers all of it, because there is only one path left to match.
Same code, three different shapes of the world, no list to maintain.
The case this still cannot see, and what to do about it
There is one situation where paths stop being able to tell anyone apart: when a bundler inlines the library into your application’s chunk. Turbopack does this for a local file: dependency during development. Library code and app code end up in literally the same generated file, so no path check on earth can separate them. The reported location degrades to that chunk path, something like:
.next/dev/server/chunks/ssr/[root-of-the-server]__ab12cd._.js:563Better than a constant, still not an answer.
The way out is not a smarter path check — the information you need is gone by then. It is source maps. The bundler already wrote down which original line each generated line came from, so you read that map and translate the chunk path back:
app/checkout/page.tsx:18That is why the caller lookup takes a sourceMaps option and resolves the frame through the build’s maps before returning it. I wrote up how that translation works, and its costs, in how to get real filenames instead of minified chunk paths in error logs.
Two small details worth stealing
Stack capture is expensive, so this is off in production. “Expensive” is easy to say, so I measured it. On Node 22.16.0, 200,000 iterations per case, the error created eight frames deep:
JSON.stringify(log entry) 0.3 - 0.9 us/op
new Error().stack (limit 10) 27 - 38 us/op
new Error().stack (limit 20) 41 - 51 us/opSerialising the log entry itself costs well under a microsecond. Capturing and materialising the stack costs tens of microseconds — about 0.03ms at the default limit and 0.05ms at 20 frames, roughly 40 to 100 times more, and that is the cheap part of the log line being dwarfed by a field you only read while debugging. Your numbers will differ with machine and stack depth; the ratio is the point. That is why captureCaller defaults to development only. It earns its cost while you are staring at a terminal. It does not earn it on every request of a live app.
Raise the frame limit, then put it back. By default Node gives you 10 stack frames (Error.stackTraceLimit). That is often enough, but not always, once you are skipping past a few layers of library code — so the capture bumps it to 20 and restores the old value immediately:
const previousLimit = Error.stackTraceLimit
Error.stackTraceLimit = 20
const stack = new Error().stack
Error.stackTraceLimit = previousLimitYou can check the default yourself with node -p "Error.stackTraceLimit". The restore line matters more than it looks. Error.stackTraceLimit is one shared global on the Error constructor. Leaving it raised would make every unrelated error anywhere else in the process build a bigger stack for the rest of its life — a side effect far larger than this one small feature has any right to cause.
The takeaway
A filter built from assumptions about where your files live is a filter with an expiry date you cannot see. It works today, it breaks on the next refactor or the first npm install, and it breaks quietly, because a wrong-but-well-formed string never looks like a failure.
A filter built from something the code can check about itself, right now, stays right while the world moves around it.
If you ever need to tell “my own code” apart from “everything else” by path, reach for import.meta.url (or __filename in CommonJS) before you reach for a list of folder names you typed from memory. And if a field in your logs has had the same value for a suspiciously long time, go and read two of them side by side.