Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Simple colorized logging for Node.js with request logger Express middleware
JavaScript
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
.gitignore
LICENSE
README.mkd
example.js
index.js
logging.js
npm-debug.log
package.json
sample.jpg
user_messages.jpg

README.mkd

node-logging

This library adds a very simple logging facility with automatic timestamping and tagging (e.g, INF:, DBG:) of log messages.

Example output:

Sample node-logging output

Installing

To install, use NPM:

npm install node-logging

Usage

You can require it as usual:

var logging = require('node-logging');

To change the log level:

logging.setLevel('error');

There are four log levels ordered by importance (from least important to more important):

  • debug: verbose debug messages
  • info: informational messages
  • error: error messages
  • critical: (bad) error messages

Setting the log level basically filters out messages of less importance. For example, setting the log level to 'error' will filter out 'info' and 'debug' messages (they simply won't be logged).

To log a single info message:

logging.inf('Message');

Each log level has it's own method:

  • debug: logging.dbg()
  • info: logging.inf()
  • error: logging.err()
  • critical: logging.bad()

Each of the logging methods take a message as first argument, and optional trace flag. Trace flag will print out the stack trace immediately following the log message if set to true. For example:

logging.bad('Woops!', true);

Using the Express middleware

If you use Express, node-logging sports a middleware that will log details about each of your requests (you can see it in the sample output at the beginning of this file).

Simply add this middleware to the stack:

app.use(logging.requestLogger);

During the request, the request object has a log property which houses a few methods you can use to log more details about the request.

To log a single message, use the push method:

req.log.push('Some point in execution');

You can also log an object (inspected) with a message:

req.log.inspect('Let\'s see what\'s in this object', someObject);

To log an asynchronous call with timer:

req.log.startTimer('MyTimer');

setTimeout(function() {
  req.log.endMyTimer('Finished async operation'),
}, 200);

The startTimer method takes a single argument, timer label. This timer label becomes part of the method that stops it. In the above example, for the label MyTimer, you will get a method called endMyTimer. If you label your timer foo, your end method will be endfoo.

All messages that you log inside your request will appear under 'User messages' section in your logs.

Here is a sample output:

Sample output of the user messages

You can terminate logging without finishing the response by calling the req.log.terminate method. This method takes a single argument msg which will be appended to the log. Normally, logging will only output the log if the response actually finishes. req.log.terminate method can be used to force log output when you know response will never finish:

app.get('/login', function(req, res, next) {

  User.find({username: req.param('username')}, function(err, user) {
    if (err) {
       req.log.terminate('Database error: ' + err);
       next(err);
       return;
    }

    // log the user in, etc, etc...

  });

});

Excluding parameters from request logger

Sometimes you don't want certain parameters logged. A good example is users' clear-text passwords. In such cases, you can set excludes to skip these parameters.

logging.setExcludes(['password', 'pw']);

By default, parameter called 'password' will be excluded. However, if you don't want to exclude the 'password' parameter, you can just set the excludes to an empty array:

logging.setExcludes([]);

The above disables any excludes.

Excluded parameters will be logged as having value '(excluded)'. This is done so that you can still see that the parameter was passed.

Sanitizing the log messages

Versions after 0.1.3 have support for sanitizing the logged messages using a global blacklist or whitelist. These lists a arrays of regexps or strings that represent a regexp pattern, that will be matched against an incoming message. The parts that match any of the regexps will be excluded (blacklist) or included (whitelist) in the final message.

By default, no blacklist or whitelist patterns are defined, so a message will appear in the log as you log them. To specify a blacklist pattern array, do it like this:

logging.setBlacklist([/\n/]);

The above must be done before any logging happens in your app. What the above does is it strips away any newlines from the messages.

To allow only alphanumeric characters and spaces in your log messages, you can use a whitelist:

logging.setWhitelist(['[a-zA-Z0-9 ]']);

This strips out all characters that are not matched by the regular expression, and therefore allows in only alphanumerics and spaces.

Note that if both blacklist and whitelist is specified, blacklist is completely ignored. Also be aware that whitelists are less efficient than blacklists, so if performance is critical, try to use blacklists.

To reset the whitelist and blacklist to default (no filtering), simply pass an empty array. Note that passing any value other than array will not work.

Something went wrong with that request. Please try again.