How to Add Logging Around Any Function
Wrap any JavaScript function with logging for arguments, results, errors and duration, handle async functions, keep this, and avoid leaking secrets. Node.js 24.

When something misbehaves, the first question is usually "what was this function called with, and what did it return?" Adding console.log lines inside the function answers it, until you have forty functions and need to remove forty lines. A wrapper answers the same question without touching the function body. It is a higher-order function that takes a function and returns one with the same behavior plus a log line on the way in and out. This post builds that wrapper on Node.js 24, makes it handle failures, promises, this and timing, and covers the mistakes that turn a logging helper into a source of bugs: swallowed errors, leaked passwords and logs that change what the program does. For the broader pattern of wrapping functions, see timing function execution.
The simplest wrapper
The wrapper receives a function and a name for the log, and returns a new function that logs, calls the original and returns its result.
function withLogging(fn, name = fn.name || "anonymous") {
return function (...args) {
console.log(`${name} called with`, args);
const result = fn.apply(this, args);
console.log(`${name} returned`, result);
return result;
};
}
function add(a, b) {
return a + b;
}
const loggedAdd = withLogging(add);
console.log(loggedAdd(2, 3));add called with [ 2, 3 ]
add returned 5
5The wrapper uses ...args to pass every argument through, whatever the count, and fn.apply(this, args) to keep the caller's this. It returns the result, because a wrapper that forgets the return changes what the function does, which is the first mistake worth avoiding. The original function is not modified, and add still works without logs.
The default name comes from fn.name. For an arrow function assigned to a variable, the engine fills that in, so const double = (n) => n * 2 has the name "double". For an anonymous function passed directly, the name is an empty string, which is why the fallback to "anonymous" is there.
Logging errors without swallowing them
A function that throws should be logged and then still throw. A wrapper that catches and does not rethrow turns a crash into a silent undefined, which is far worse than no logging.
function withLogging(fn, name = fn.name || "anonymous") {
return function (...args) {
console.log(`${name} called with`, args);
try {
const result = fn.apply(this, args);
console.log(`${name} returned`, result);
return result;
} catch (error) {
console.log(`${name} threw ${error.name}: ${error.message}`);
throw error;
}
};
}
const parse = withLogging(function parse(text) {
return JSON.parse(text);
});
try {
parse("{oops");
} catch (error) {
console.log("caller saw", error.name);
}parse called with [ '{oops' ]
parse threw SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
caller saw SyntaxErrorThe wrapper logs the error and rethrows the very same object with throw error, so the stack trace and the type are preserved. Throwing a new Error with the old message would lose the original stack, and callers who check instanceof SyntaxError would stop matching. The exact text of the SyntaxError message varies between Node.js versions and is produced by the engine, so your terminal may show different wording for the same bad input.
Async functions are the common trap
An async function returns a promise immediately. The wrapper above logs "returned" with Promise { <pending> } and never learns whether the call worked.
async function fetchUser(id) {
await new Promise((resolve) => setTimeout(resolve, 5));
return { id };
}
const loggedFetch = withLogging(fetchUser);
const promise = loggedFetch(1);
console.log("got a promise:", promise instanceof Promise);
console.log(await promise);fetchUser called with [ 1 ]
fetchUser returned Promise { <pending> }
got a promise: true
{ id: 1 }The log claims the function returned a pending promise, which is true and useless. If the promise later rejects, the wrapper's catch never runs, since nothing was thrown synchronously. The fix is to detect a promise result and attach the logging to it.
const isThenable = (value) => value !== null && typeof value?.then === "function";
function withLogging(fn, name = fn.name || "anonymous") {
return function (...args) {
console.log(`${name} called with`, args);
const onSuccess = (result) => {
console.log(`${name} returned`, result);
return result;
};
const onFailure = (error) => {
console.log(`${name} threw ${error.name}: ${error.message}`);
throw error;
};
try {
const result = fn.apply(this, args);
return isThenable(result) ? result.then(onSuccess, onFailure) : onSuccess(result);
} catch (error) {
return onFailure(error);
}
};
}
const loggedFetch2 = withLogging(async function fetchUser(id) {
if (id < 0) throw new RangeError("negative id");
return { id };
});
console.log(await loggedFetch2(1));
try {
await loggedFetch2(-1);
} catch (error) {
console.log("caller saw", error.name);
}fetchUser called with [ 1 ]
fetchUser returned { id: 1 }
{ id: 1 }
fetchUser called with [ -1 ]
fetchUser threw RangeError: negative id
caller saw RangeErrorNow the log shows the resolved value, and a rejection is logged and propagated. The wrapper returns result.then(onSuccess, onFailure), a new promise that resolves to the same value, so the caller still gets what the original would have given. A synchronous function takes the other branch and behaves exactly as before.
Adding timing
The wrapper is the natural place to measure duration. Use performance.now(), which is monotonic and has sub-millisecond resolution, instead of Date.now(), which can jump when the system clock changes.
function withTiming(fn, name = fn.name || "anonymous") {
return function (...args) {
const start = performance.now();
const done = (label) => {
const ms = performance.now() - start;
console.log(`${name} ${label} in ${ms.toFixed(1)} ms`);
};
try {
const result = fn.apply(this, args);
if (isThenable(result)) {
return result.finally(() => done("settled"));
}
done("finished");
return result;
} catch (error) {
done("failed");
throw error;
}
};
}
const slow = withTiming(async function slow() {
await new Promise((resolve) => setTimeout(resolve, 20));
});
await slow();slow settled in 21.3 msThe number depends on the machine and scheduler, so yours will differ, and a timer set for twenty milliseconds typically fires a little late. finally runs on both success and failure and passes the original outcome through, which is why it fits here.
Do not log secrets
Logging every argument is a security problem the moment an argument is a password, a token or a card number. Logs travel to files, aggregators and support tickets, and they live far longer than the request.
function redact(value, secretKeys = ["password", "token", "authorization"]) {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) return value.map((item) => redact(item, secretKeys));
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [
key,
secretKeys.includes(key.toLowerCase()) ? "[redacted]" : redact(inner, secretKeys),
]),
);
}
const login = withLogging(function login(credentials) {
return credentials.user;
});
console.log(redact([{ user: "ada", password: "hunter2", profile: { token: "abc" } }]));[ { user: 'ada', password: '[redacted]', profile: { token: '[redacted]' } } ]Pass redact(args) to the log call inside the wrapper, so the real arguments still go to the function. Matching on key names is a heuristic. It catches the common cases and misses a secret in a field called x, so for sensitive functions the safer rule is to log only an allow list of fields, or nothing but the function name.
There is a size problem too. Logging a large array or a big object on every call fills the log and can slow the program. Truncate long values, or log only a summary such as the length.
Keeping this and the function's identity
The wrapper keeps this, but it replaces the function, and a few properties change: name and length of the wrapper are those of the anonymous function it returns. For debugging that rarely matters. If code inspects them, copy them over.
function withLogging(fn, name = fn.name || "anonymous") {
const wrapped = function (...args) {
return fn.apply(this, args);
};
Object.defineProperty(wrapped, "name", { value: name });
Object.defineProperty(wrapped, "length", { value: fn.length });
return wrapped;
}
console.log(withLogging(function add(a, b) {}).name);
console.log(withLogging(function add(a, b) {}).length);add
2Both properties are configurable on functions, so defineProperty works. And wrapping a method on an object works as long as you keep the original this: obj.method = withLogging(obj.method) and calls still reach the right object, because the wrapper passes this along.
Logging a whole object
To log every method of an object, wrap each function property.
function logMethods(object, name) {
for (const key of Object.keys(object)) {
if (typeof object[key] === "function") {
object[key] = withLogging(object[key], `${name}.${key}`);
}
}
return object;
}This modifies the object in place, which is convenient and invasive. A Proxy with a get trap can do the same without changing the original, wrapping functions as they are read, and it covers methods added later. For quick debugging in a Node.js session, either is fine; for production, prefer a real logger such as the one built into your framework and log at the boundaries, such as requests, jobs and external calls, instead of on every function.
Turning it off
A logging wrapper that cannot be switched off will eventually be left in production. Read a flag such as process.env.DEBUG_CALLS once when the module loads, and return the original function unchanged when it is not set. The wrapped and unwrapped versions then behave identically, and the cost in production is zero because no wrapper exists. Apply the wrapper in one place, such as the module that exports the function, so that removing it later means deleting a single line and not hunting through call sites.
Keep the log output structured when you can. A line such as add called with [ 2, 3 ] is easy to read in a terminal, but a log aggregator searches fields better than sentences, so a real logger call with the function name and arguments as separate fields is worth the extra line.


