HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

NodeJS logging module

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
modulenodejslogging

Problem

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
//'info','warn','error','log','system','socketio','sql'
};

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.prepare

Solution

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.

Context

StackExchange Code Review Q#94042, answer score: 3

Revisions (0)

No revisions yet.