fuzelog

A simple node.js logger fusing log.js with log4js's layouts and colors, supporting console and file logging.

npm install fuzelog
14 downloads in the last week
19 downloads in the last month

fuzelog

fuzelog is a fusion of the log.js module by TJ Hollowaychuck with the layout and formatting options from log4js. Additionally, there is printf-like functionality and the ability to pass functions called only when the level is correct.

The logic behind this module is that, when you are logging copious amounts of data, you often find yourself doing:

log.debug('The user object is: '+JSON.stringify(userObj));

And this code runs in production. Though it produces no output to the log file or the console, the arguement evaluation is always done, which can mean many calls to functions like JSON.stringify. The goal of fuzelog is to provide a means to avoid unneccessary evaluations. fuzelog gives you 2 ways to do this:

  1. printf-style argument evaluation done only if the right logging is in place
  2. function arguments that, when evaluated, produce a string and are called only when the logging level is correct

The original modules from which fuzelog borrowed code:

Module Description
log4jsRobust and solid logging API which is very simmilar to the Java logging framework Log4j
log.jsSuper light-weight nodejs logging + streaming log reader

Installation

$ npm install fuzelog

Example

The original usage of log.js remains down to the constructor arguments, however, if the first argument is an object, FuzeLog uses the object as a configuration object.

The log level defaults to debug, however we specify info below and the output stream is set to the file 'example.log':

var Log = require('fuzelog');
var logConfig = {
    level: 'info',              // INFO logging level
    name: 'fuzelog',            // Category name, shows as %c in pattern

    // FileStream to log to (can be file name or a stream)
    file: __dirname + '/example.log',

    fileFlags: 'a',             // Flags used in fs.createWriteStream to create log file
    consoleLogging: true,       // Flag to direct output to console
    colorConsoleLogging: true,  // Flag to color output to console

    // Usage of the log4js layout
    logMessagePattern: '[%d{ISO8601}] [%p] %c - %m{1}'
};

var log = new Log(logConfig);
log.debug('You will not see this - preparing email');
log.info('sending email');
log.error('failed to send email');

var obj = { a: 667,
            b: 'This is a string.',
            c: 22 };
log.emergency('failed to send %s, object: %j', 'email', obj);

The output for the previous exampls is:

[2013-02-22 14:55:25.816] [INFO] fuzelog - sending email
[2013-02-22 14:55:25.819] [ERROR] fuzelog - failed to send email
[2013-02-22 14:55:25.820] [EMERGENCY] fuzelog - failed to send email, object: {"a":667,"b":"This is a string.","c":22}

We can also use %s much like console.log() to pass arguments:

 log.error('oh no, failed to send mail to %s.', 'Edmond');

Output:

 [2013-02-22 14:58:23.063] [ERROR] fuzelog - oh no, failed to send mail to Edmond.

fuzelog also accepts a function and will only call that function if the appropriate log level exists.

var Log = require('fuzelog');
var log = new Log();

function logFunc() {
    // fuzelog uses sprintf.js which places sprintf and printf into the global scope
    return sprintf('%s facility reports %d %s.', 'The fuzelog', 67, 'ducks');
};

// we don't de-reference the function now, fuzelog will evaluate it
// if the logging level is correct
log.info(logFunc);

Output:

[2013-02-22 14:59:36.892] [INFO] Unnamed - The fuzelog facility reports 67 ducks.

Notes:

  • fuzelog assumes utf8 encoded data.
  • fuzelog uses sprintf.js which places printf and a sprintf in the global scope and onto the String prototype. See the sprintf.js github page for more information.

Log Levels

The log levels mirror that of syslog:

Log Level Meaning
EMERGENCY system is unusable
ALERT action must be taken immediately
CRITICAL the system is in critical condition
ERROR error condition
WARNING warning condition
NOTICE a normal but significant condition
INFO a purely informational message
DEBUG messages to debug an application

When specifying the log level, fuzelog looks for an object in its constructor with a property named "level" having a string with the log level name (case does not matter).

API

lvlColors

Color settings for console logging. When constructing the logger, you can sepcify the colors used on the console by setting property 'debugLvlColors' on the configuration object passed to the Log constructor. However, you must also turn on colorConsoleLogging which by default, is false.

Example:

var Log = require('fuzelog');
var lvlColors = {
    EMERGENCY:  'red',
    ALERT:      'red',
    CRITICAL:   'red',
    ERROR:      'red',
    WARNING:    'yellow',
    NOTICE:     'grey',
    INFO:       'grey',
    DEBUG:      'grey'
};

var log = new Log( { colorConsoleLogging: true, debugLvlColors: lvlColors } );
log.warning('a warning message');

lvlEffects

In addition to colors, it is possible to apply 1 additional effect to the log line, e.g. bold, underline, inverse. Simple set the 'debugLvlConsoleFx' property to an object in the configuration object passed to the Log constructor and on that object, set the facility name with the effect desired. However, you must also turn on colorConsoleLogging which by default, is false.

var Log = require('fuzelog');
var lvlEffects = {
    EMERGENCY:  'inverse',
    ALERT:      false,
    CRITICAL:   false,
    ERROR:      false,
    WARNING:    'inverse',
    NOTICE:     false,
    INFO:       false,
    DEBUG:      'underline',
};

var logConfig = {
    colorConsoleLogging: true,     // Use colors on the console
    debugLvlConsoleFx: lvlEffects, // set font fx
};

var log = new Log(logConfig);
log.warning('a warning message');

Log() (constructor)

The constructor for fuzelog, called 'Log', takes an optional configuration object to set various options. If the config object is not set, fuzelog will log to the console only, using default colors and the logging level is debug.

The following settings are available in the configuration object:

Option Meaning
file String|Stream, Path to the file to write log. If not specified, file logging does not happen.
colorConsoleLoggingIf true, colors and effects (bold, inverse and underline) are displayed to the console. False by default.
consoleLogging Boolean, If true, logging to the console will occur. If not specified, logging to the console is true by default.
debugLvlColors Object, An object contarining the facility names as keys (uppercase), with colors for each facility to display, e.g. green, blue, red, etc. If not specified and colorConsoleLogging is true, default colors are used.
debugLvlConsoleFx Object, An object contarining the facility names as keys (uppercase), with font effects in quotes, e.g. bold, inverse, underline.
level String, e.g. "info", sets the logging level, no messages below this level are visible.
logMessagePattern String, a template from log4js to specificy how each log line should appear, e.g. '[%d{ISO8601}] [%p] %c - %m{1}'
name String The name of the log. If you use the layout via logMessagePattern, the name is %c. The default name is "Unamed".
The following format descriptors exist for the logMessagePattern:
Descriptor Meaning
%r time in toLocaleTimeString format
%p log level
%c log category
%m log data
%d date in various formats
%% %
%n newline

If the logMessagePattern is '[%d{ISO8601}] [%p] %c - %m{1}' then the following line:

log.info('an info message');

will produce the following output:

[2013-06-23 18:11:24.452] [INFO] example log - an info message

You can find more information on log message patterns at the Apache log4j PatternLayout Page.

Log.emergency(msg:String)

Display a log message in the emergency facility.

Log.alert(msg:String)

Display a log message in the alert facility.

Log.critical(msg:String)

Display a log message in the critical facility.

Log.error(msg:String)

Display a log message in the error facility.

Log.warning(msg:String)

Display a log message in the warning facility.

Log.notice(msg:String)

Display a log message in the notice facility.

Log.info(msg:String)

Display a log message in the info facility.

Log.debug(msg:String)

Display a log message in the debug facility.

License

The MIT License Copyright (c) 2013,2014 Edmond Meinfelder

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

npm loves you