Skip to content

Instantly share code, notes, and snippets.

@constantology
Created July 24, 2014 09:39
Show Gist options
  • Save constantology/5f04d5782c1cc019722f to your computer and use it in GitHub Desktop.
Save constantology/5f04d5782c1cc019722f to your computer and use it in GitHub Desktop.
using node's process to emit events to log stuff from anywhere
// use like this:
// process.emit( 'app:log', module, arg1, arg2, ..., argN );
var Module = require('module');
function logConsole(method, module) {
var args = [(new Date()).toJSON(), method];
var index = 1;
if (module instanceof Module) {
args.push(module.id);
index = 2;
}
args.push.apply(args, Array.prototype.slice.call(arguments, index));
console.log.apply(console, args);
}
['debug', 'error', 'info', 'log', 'warn'].forEach( function(consoleMethod) {
process.on('app:' + consoleMethod, logConsole.bind(null, consoleMethod.toUpperCase()));
} );
@constantology
Copy link
Author

this was jeffwad's original idea

@iancrowther
Copy link

nice

@RangerMauve
Copy link

This should be on NPM.

@mscdex
Copy link

mscdex commented Jul 24, 2014

FWIW you should avoid Array.prototype.slice.call(arguments, index) style calls if you care about performance since that will make logConsole unoptimizable by v8. Creating a new array and appending to it in a for-loop will avoid this deoptimization.

@dougwilson
Copy link

The module depd will emit deprecation events on process if there is a listener, automatically suppressing output to STDERR for centralized logging in mind similar to this.

@ketansp
Copy link

ketansp commented Mar 22, 2017

Can you please specify which versions of node are supported? I cant get it working in 6.6.0

@cryptiklemur
Copy link

WHy

@nokome
Copy link

nokome commented Oct 17, 2019

In case it's of interest we've implemented this approach, with some sugar, and browser compatibility, in https://github.com/stencila/logga

@constantology
Copy link
Author

Hey @nokome,

My friend @jeffwad — whom I commented above as, having the original idea for this — and I had completely forgotten about it when I got an email notification of your comment from github. 😅

I'm glad posting it gave you some value/inspiration, however small... 😊

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