What is log4js?
The log4js npm package is a logging library for Node.js, inspired by the Java-based Log4j. It provides a flexible logging system that can be configured to log to the console, to files, or to external logging services. It supports multiple log levels, categories, and appenders, allowing for fine-grained control over logging output.
What are log4js's main functionalities?
Basic Logging
This code sets up log4js to log messages to the standard output (console). It configures an appender named 'out' that writes to stdout and sets the default logging level to 'info'.
const log4js = require('log4js');
log4js.configure({
appenders: { 'out': { type: 'stdout' } },
categories: { default: { appenders: ['out'], level: 'info' } }
});
const logger = log4js.getLogger();
logger.info('Informational message');
File Appender
This code configures log4js to write log messages to a file named 'app.log' in the 'logs' directory. It creates a file appender and sets the logging level to 'warn'.
const log4js = require('log4js');
log4js.configure({
appenders: { 'file': { type: 'file', filename: 'logs/app.log' } },
categories: { default: { appenders: ['file'], level: 'info' } }
});
const logger = log4js.getLogger();
logger.warn('Warning message');
Log Levels
This code demonstrates the use of different log levels available in log4js. Each level represents a different severity of logging, with 'trace' being the least severe and 'fatal' being the most severe.
const log4js = require('log4js');
const logger = log4js.getLogger('myCategory');
logger.trace('Trace message');
logger.debug('Debug message');
logger.info('Info message');
logger.warn('Warn message');
logger.error('Error message');
logger.fatal('Fatal message');
Multiple Appenders and Categories
This code shows how to configure multiple appenders and categories. The 'default' category logs to both the console and a file, while the 'special' category logs only to a file and only logs messages at the 'error' level or higher.
const log4js = require('log4js');
log4js.configure({
appenders: {
'out': { type: 'stdout' },
'file': { type: 'file', filename: 'logs/app.log' }
},
categories: {
default: { appenders: ['out', 'file'], level: 'info' },
special: { appenders: ['file'], level: 'error' }
}
});
const defaultLogger = log4js.getLogger();
defaultLogger.info('Default category, logged to console and file');
const specialLogger = log4js.getLogger('special');
specialLogger.error('Special category, logged to file only');
Other packages similar to log4js
winston
Winston is a multi-transport async logging library for Node.js. Like log4js, it supports multiple transports (e.g., file, console, HTTP) and custom log levels. It is highly configurable and is considered one of the most popular logging solutions in the Node.js ecosystem, often compared to log4js for its rich features and flexibility.
bunyan
Bunyan is a simple and fast JSON logging library for Node.js services. It includes a CLI tool for pretty-printing log files. Bunyan's focus on JSON logging format makes it particularly suitable for use in large-scale distributed systems where log aggregation and analysis are important. It is less configurable than log4js and winston but is valued for its simplicity and streaming capabilities.
pino
Pino is a very low-overhead Node.js logger that outputs logs in JSON format. It is designed for performance and can be significantly faster than other logging libraries like log4js, especially in high-throughput scenarios. Pino's API is relatively minimal compared to log4js, focusing on delivering the best performance possible.
log4js-node
This is a conversion of the log4js
framework to work with node. I've mainly stripped out the browser-specific code
and tidied up some of the javascript. It includes a basic file logger, with log rolling based on file size, and also replaces node's console.log functions.
NOTE: in v0.2.x require('log4js') returned a function, and you needed to call that function in your code before you could use it. This was to make testing easier. v0.3.x make use of felixge's sandbox-module, so we don't need to return a function.
installation
npm install log4js
tests
Tests now use vows, run with vows test/*.js
.
usage
Minimalist version:
var log4js = require('log4js');
var logger = log4js.getLogger();
logger.debug("Some debug messages");
By default, log4js outputs to stdout with the coloured layout (thanks to masylum), so for the above you would see:
[2010-01-17 11:43:37.987] [DEBUG] [default] - Some debug messages
See example.js:
var log4js = require('log4js'); //note the need to call the function
log4js.addAppender(log4js.consoleAppender());
log4js.addAppender(log4js.fileAppender('logs/cheese.log'), 'cheese');
var logger = log4js.getLogger('cheese');
logger.setLevel('ERROR');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');
Output:
[2010-01-17 11:43:37.987] [ERROR] cheese - Cheese is too ripe!
[2010-01-17 11:43:37.990] [FATAL] cheese - Cheese was breeding ground for listeria.
configuration
You can either configure the appenders and log levels manually (as above), or provide a
configuration file (log4js.configure('path/to/file.json')
) explicitly, or just let log4js look for a file called log4js.json
(it looks in the current directory first, then the require paths, and finally looks for the default config included in the same directory as the log4js.js
file).
An example file can be found in test/log4js.json
. An example config file with log rolling is in test/with-log-rolling.json
.
By default, the configuration file is checked for changes every 60 seconds, and if changed, reloaded. This allows changes to logging levels
to occur without restarting the application.
To turn off configuration file change checking, configure with:
var log4js = require('log4js');
log4js.configure(undefined, {}); // load 'log4js.json' from NODE_PATH
Or:
log4js.configure('my_log4js_configuration.json', {});
To specify a different period:
log4js.configure(undefined, { reloadSecs: 300 }); // load 'log4js.json' from NODE_PATH
You can also pass an object to the configure function, which has the same properties as the json versions.
connect/express logger
A connect/express logger has been added to log4js, by danbell. This allows connect/express servers to log using log4js. See example-connect-logger.js.
var log4js = require('./lib/log4js');
log4js.addAppender(log4js.consoleAppender());
log4js.addAppender(log4js.fileAppender('cheese.log'), 'cheese');
var logger = log4js.getLogger('cheese');
logger.setLevel('INFO');
var app = require('express').createServer();
app.configure(function() {
app.use(log4js.connectLogger(logger, { level: log4js.levels.INFO }));
});
app.get('/', function(req,res) {
res.send('hello world');
});
app.listen(5000);
The options object that is passed to log4js.connectLogger supports a format string the same as the connect/express logger. For example:
app.configure(function() {
app.use(log4js.connectLogger(logger, { level: log4js.levels.INFO, format: ':method :url' }));
});
author (of this node version)
Gareth Jones (csausdev - gareth.jones@sensis.com.au)
License
The original log4js was distributed under the Apache 2.0 License, and so is this. I've tried to
keep the original copyright and author credits in place, except in sections that I have rewritten
extensively.