180

Is there any library which will help me to handle logging in my Node.Js application? All I want to do is, I want to write all logs into a File and also I need an options like rolling out the file after certain size or date.


I have incorporated log4js im trying to keep all the configuration details in one file and use only the methods in other application files for ease of maintenance. But it doesnt work as expected. Here is what I'm trying to do

var log4js = require('log4js'); 
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');


var traceLogger = function (message) {
        logger.trace('message');
    };

var errorLogger = function (message) {
        logger.trace(message);
    };


exports.trace = traceLogger;
exports.error = errorLogger;

I have included this file in other files and tried

log.error ("Hello Error Message");

But it is not working. Is there anything wrong in this ?

Ankur Loriya
  • 2,858
  • 8
  • 27
  • 57
syv
  • 3,268
  • 6
  • 26
  • 38
  • 1
    log4js seems ok. you have set ther error level wrong. it should be: logger.setLevel(log4js.levels.ERROR); – Boklucius Feb 27 '14 at 15:49

9 Answers9

199

Winston is a pretty good logging library. You can write logs out to a file using it.

Code would look something like:

var winston = require('winston');

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
  ],
  exceptionHandlers: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
  ],
  exitOnError: false
});

module.exports = logger;

You can then use this like:

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

logger.info('log to file');
zs2020
  • 52,221
  • 27
  • 148
  • 209
Charlie Key
  • 3,266
  • 1
  • 17
  • 12
  • 5
    @TravisWebb - https://github.com/flatiron/winston/issues/294 & https://github.com/flatiron/winston/issues/280 – ostergaard Nov 18 '13 at 10:45
  • 3
    I've used winston for a long time. It has gotten buggy and I have ditched it in favor of npmlog. – airportyh Nov 23 '13 at 13:03
  • 8
    @everyone, seems winston is being maintained again... https://github.com/flatiron/winston/network – Daithí Dec 20 '13 at 14:22
  • Just a quick note: call logger.cli() in the above example for colored command line output. – Duncan Oct 14 '14 at 16:38
  • @nelsonic - I honestly can't decide whether you're trying to be antagonistic or simply didn't read all the comments - which is it? – ostergaard Mar 14 '15 at 02:43
  • @ajostergaard you're absolutely correct, your later comment was hidden by the UI (and I neglected to expand). my bad. sorry. what are you using *now* for logging BTW? (still winston?) thanks! – nelsonic Mar 14 '15 at 20:30
  • 1
    Winston doesn't allow for its configuration to be defined and read from a .json file. Poor design, imo. – miniml Oct 26 '15 at 01:47
  • You can obviously write 10 lines yourself that read a .json file and configure Winston. Not adding that too is great design. – Hejazzman Feb 11 '16 at 23:54
  • Upvoted but a little strange, we are using a third party library for this, doesnt Node have an inbuilt logger like the logging package in Python? – PirateApp Mar 05 '19 at 04:23
59

Scribe.JS Lightweight Logger

I have looked through many loggers, and I wasn't able to find a lightweight solution - so I decided to make a simple solution that is posted on github.

  • Saves the file which are organized by user, date, and level
  • Gives you a pretty output (we all love that)
  • Easy-to-use HTML interface

I hope this helps you out.

Online Demo

http://bluejamesbond.github.io/Scribe.js/

Secure Web Access to Logs

A

Prints Pretty Text to Console Too!

A

Web Access

A

Github

https://github.com/bluejamesbond/Scribe.js

Mathew Kurian
  • 5,658
  • 5
  • 39
  • 71
31

Log4js is one of the most popular logging library for nodejs application.

It supports many cool features:

  1. Coloured console logging
  2. Replacement of node's console.log functions (optional)
  3. File appender, with log rolling based on file size
  4. SMTP, GELF, hook.io, Loggly appender
  5. Multiprocess appender (useful when you've got worker processes)
  6. A logger for connect/express servers
  7. Configurable log message layout/patterns
  8. Different log levels for different log categories (make some parts of your app log as DEBUG, others only ERRORS, etc.)

Example:

  1. Installation: npm install log4js

  2. Configuration (./config/log4js.json):

    {"appenders": [
        {
            "type": "console",
            "layout": {
                "type": "pattern",
                "pattern": "%m"
            },
            "category": "app"
        },{
            "category": "test-file-appender",
            "type": "file",
            "filename": "log_file.log",
            "maxLogSize": 10240,
            "backups": 3,
            "layout": {
                "type": "pattern",
                "pattern": "%d{dd/MM hh:mm} %-5p %m"
            }
        }
    ],
    "replaceConsole": true }
    
  3. Usage:

    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    // log4js.getLogger("app") will return logger that prints log to the console
    logger.debug("Hello log4js");// store log in file
    
Tho
  • 17,326
  • 6
  • 51
  • 41
11

You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.

You can find this module here https://github.com/isaacs/npmlog

sam100rav
  • 3,516
  • 4
  • 23
  • 42
6

The "logger.setLevel('ERROR');" is causing the problem. I do not understand why, but when I set it to anything other than "ALL", nothing gets printed in the file. I poked around a little bit and modified your code. It is working fine for me. I created two files.

logger.js

var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');

var getLogger = function() {
   return logger;
};

exports.logger = getLogger();

logger.test.js

var logger = require('./logger.js')

var log = logger.logger;

log.error("ERROR message");
log.trace("TRACE message");

When I run "node logger.test.js", I see only "ERROR message" in test.log file. If I change the level to "TRACE" then both lines are printed on test.log.

  • 2
    https://logging.apache.org/log4j/1.2/manual.html Loggers may be assigned levels. The set of possible levels, that is: TRACE, DEBUG, INFO, WARN, ERROR and FATAL A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. – Shawn C. Apr 10 '14 at 16:57
3

Winston is strong choice for most of the developers. I have been using winston for long. Recently I used winston with with papertrail which takes the application logging to next level.

Here is a nice screenshot from their site.

enter image description here

How its useful

  • you can manage logs from different systems at one place. this can be very useful when you have two backend communicating and can see logs from both at on place.

  • Logs are live. you can see realtime logs of your production server.

  • Powerful search and filter

  • you can create alerts to send you email if it encounters specific text in log.

and you can find more http://help.papertrailapp.com/kb/how-it-works/event-viewer/

A simple configuration using winston,winston-express and winston-papertrail node modules.

import winston from 'winston';
import expressWinston from 'express-winston';
//
// Requiring `winston-papertrail` will expose
// `winston.transports.Papertrail`
//
require('winston-papertrail').Papertrail;
// create winston transport for Papertrail
var winstonPapertrail = new winston.transports.Papertrail({
  host: 'logsX.papertrailapp.com',
  port: XXXXX
});
app.use(expressWinston.logger({
  transports: [winstonPapertrail],
  meta: true, // optional: control whether you want to log the meta data about the request (default to true)
  msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
  expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
  colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
  ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
}));
vinesh
  • 4,135
  • 5
  • 38
  • 45
  • 1
    This still works, however after the upgrade of winston to v3 you get a warning: "Papertrail is a legacy winston transport. Consider upgrading". There's an upgrade to the transport currently outstanding. – Jim Jimson Oct 23 '18 at 06:07
2

A 'nodejslogger' module can be used for simple logging. It has three levels of logging (INFO, ERROR, DEBUG)

var logger = require('nodejslogger')
logger.init({"file":"output-file", "mode":"DIE"})

D : Debug, I : Info, E : Error

logger.debug("Debug logs")
logger.info("Info logs")
logger.error("Error logs")

The module can be accessed at : https://www.npmjs.com/package/nodejslogger

0

Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

The fix is to change logger.trace to logger.error in the body of errorLogger.

0

Each answer is 5 6 years old, so bit outdated or depreciated. Let's talk in 2020.

simple-node-logger is simple multi-level logger for console, file, and rolling file appenders. Features include:

  1. levels: trace, debug, info, warn, error and fatal levels (plus all and off)

  2. flexible appender/formatters with default to HH:mm:ss.SSS LEVEL message add appenders to send output to console, file, rolling file, etc

  3. change log levels on the fly

  4. domain and category columns

  5. overridable format methods in base appender

  6. stats that track counts of all log statements including warn, error, etc

You can easily use it in any nodejs web application:

   // create a stdout console logger
  const log = require('simple-node-logger').createSimpleLogger();

or

  // create a stdout and file logger
  const log = require('simple-node-logger').createSimpleLogger('project.log');

or

  // create a custom timestamp format for log statements
  const SimpleNodeLogger = require('simple-node-logger'),
  opts = {
      logFilePath:'mylogfile.log',
      timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
   },
  log = SimpleNodeLogger.createSimpleLogger( opts );

or

  // create a file only file logger
  const log = require('simple-node-logger').createSimpleFileLogger('project.log');

or

  // create a rolling file logger based on date/time that fires process events
  const opts = {
      errorEventName:'error',
       logDirectory:'/mylogfiles', // NOTE: folder must exist and be writable...
        fileNamePattern:'roll-<DATE>.log',
         dateFormat:'YYYY.MM.DD'
  };
  const log = require('simple-node-logger').createRollingFileLogger( opts );

Messages can be logged by

  log.info('this is logged info message')
  log.warn('this is logged warn message')//etc..

PLUS POINT: It can send logs to console or socket. You can also append to log levels.

This is the most effective and easy way to handle logs functionality.

  • I want to use two simple-node-logger instances in two node processes, writing to the same log file. Is that possible, or how can I write a database appender to log the outputs to a central database. – user1894504 Oct 08 '20 at 14:16