nodejs log to file for multiple modules

There are several projects provide the ability to log to file for nodejs like log4js, winston etc.

I picked winston for no specific reason.

init setup is pretty simple, just follow what is written in Github.

To make it be able to be shared by multiple modules, we need some tweaks.

First we need a config file:

we name the file logConfig.js and put it under log directory.

 * Created by LeOn on 2/21/15.

var logger = require('winston');
var moment = require('moment');

    debug: 0,
    info: 1,
    silly: 2,
    warn: 3,
    error: 4
    debug: 'green',
    info: 'cyan',
    silly: 'magenta',
    warn: 'yellow',
    error: 'red'

logger.add(logger.transports.Console, {
    timestamp: function () {
        return getCurrentTime();
    }, level: 'debug', colorize: true
//specify the json:false so that it does not write json to the log file which not that human readable.
logger.add(logger.transports.File, {
    json: false, timestamp: function () {
        return getCurrentTime();
    }, filename: 'log/contactApp.log', level: 'debug'

//use moment to format to local time, it has better looking than the js' own toLocaleTime()
function getCurrentTime()
    return new moment().format("YYYY-M-D hh:mm:ss-SSS");

module.exports = logger;

Then in the app.js or server.js

var logger = require('./log/logConfig.js');

Finally in files from other moduels

 var logger = require('winston'); 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s