This code is for a NodeJS logging module. I created it because I wanted to find a way to log different type of things but not show them all at the same time. I also wanted to format the logs in a custom manner.

Is there anything I could do to improve this code, such as making it shorter? Are there still any bugs?

// original way of adding config
//var config  = require('config');
var config  = {
     debug: true,
     debugArray:['info','warn']//add remove log types to show

var dateFormat = require('dateformat');
var chalk = require('chalk');
var path = require('path');
var Logger = Object.create({});
var define = Object.defineProperty.bind(undefined, Logger);

function doLog(msg, type, search, stack){
  if(config.debug && ( config.debugArray.indexOf(search) > -1)){
      var fdate = dateFormat(new Date(), 'yyyy-mm-dd hh:MM:ss.l');
      var fFilename = stack.getFileName().substr(path.dirname(require.main.filename).length + 1);
      var lineNumber = stack.getLineNumber();
      var preMsg =  fdate + ' ' +  type + ' [' + chalk.yellow(fFilename + ':' + lineNumber) + '] ';
      console.log(preMsg + msg);
Logger.log = function (txt){
  doLog(txt,'LOG', 'log', this.stack[1]);

Logger.system = function (txt){
  doLog(chalk.gray(txt), chalk.gray('SYSTEM'), 'system', this.stack[1]);

Logger.socketio = function (txt){
  doLog(chalk.cyan(txt), chalk.cyan('SOCKET'), 'socketio', this.stack[1]);

Logger.sql = function (txt){
  doLog(txt, chalk.cyan('SQL'), 'sql', this.stack[1]);

Logger.info = function (txt){
  doLog(chalk.cyan(txt), chalk.cyan('INFO'), 'info', this.stack[1]);

Logger.warn = function (txt){
  doLog(chalk.yellow(txt), chalk.yellow('WARN'), 'warn', this.stack[1]);

Logger.error = function (txt){
  doLog(chalk.red(txt), chalk.red('ERROR'), 'error', this.stack[1]);

define('stack', {
  get: function(){
    var originalStack = Error.prepareStackTrace;
    Error.prepareStackTrace = function(_, stack){ return stack; };
    var err = new Error();
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack;
    Error.prepareStackTrace = originalStack;
    return stack;

module.exports = Logger;

1 Answer 1


You have an unneeded comma in line 5. Although it won't make Node.js crash it is invalid JavaScript. And as you are using semicolons you should use them everywhere. So you should end your statement in line 7 with a semicolon.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.