Skip to content

Instantly share code, notes, and snippets.

@wesbos
Created January 8, 2024 15:55
Show Gist options
  • Save wesbos/9b2462478e62d8633367d98c0d8d439d to your computer and use it in GitHub Desktop.
Save wesbos/9b2462478e62d8633367d98c0d8d439d to your computer and use it in GitHub Desktop.
console.log line numbers in Node.js
// Use like this: node --import logger.js yourapp.js
import path from 'path';
const { log } = console;
[`debug`, `log`, `warn`, `error`, `table`, `dir`].forEach((methodName) => {
const originalLoggingMethod = console[methodName];
console[methodName] = (...args) => {
const originalPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const callee = new Error().stack[1];
Error.prepareStackTrace = originalPrepareStackTrace;
const relativeFileName = path
.relative(process.cwd(), callee.getFileName())
.replace(process.cwd(), ``)
.replace(`file:/`, ``);
// Log in dark grey
const label = `${relativeFileName}:${callee.getLineNumber()}`;
log(`🪵 \x1b[90m%s\x1b[0m`, label);
originalLoggingMethod(...args);
};
});
@ljharb
Copy link

ljharb commented Jan 8, 2024

Awesome! I modified it to the following, so it'd work in more node versions (down to node 6), and then used NODE_OPTIONS="-r 'path/to/file'" in my shell profile so it'd be automatic, and aliased node to node $NODE_OPTIONS to handle node versions 1 - 5. Still haven't figured out node < 1 tho :-)

// from https://gist.github.com/wesbos/9b2462478e62d8633367d98c0d8d439d
// Use like this: node -r logger.js yourapp.js

var path = require('path');

var log = Function.call.bind(console.log, console);
['debug', 'log', 'warn', 'error', 'table', 'dir'].forEach(function (methodName) {
  var originalLoggingMethod = Function.apply.bind(console[methodName], console);
  console[methodName] = function () {
    var originalPrepareStackTrace = Error.prepareStackTrace;
    Error.prepareStackTrace = function (_, stack) { return stack; };
	var callee = new Error().stack[1];
    Error.prepareStackTrace = originalPrepareStackTrace;
    var relativeFileName = path
      .relative(process.cwd(), callee.getFileName())
      .replace(process.cwd(), '')
      .replace('file:/', '');
    // Log in dark grey
    var label = relativeFileName + ':' + callee.getLineNumber();
    log('🪵 \x1b[90m%s\x1b[0m', label);
    originalLoggingMethod(arguments);
  };
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment