winston
A multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs."
Installation
Installing npm (node package manager)
curl http://npmjs.org/install.sh | sh
Installing winston
[sudo] npm install winston
Motivation
Winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file.
There also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible.
Usage
There are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose.
Using the Default Logger
The default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger:
var winston = require('winston');
winston.log('info', 'Hello distributed log files!');
winston.info('Hello again distributed logs');
By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods:
winston.add(winston.transports.File, { filename: 'somefile.log' });
winston.remove(winston.transports.Console);
For more documenation about working with each individual transport supported by Winston see the "Working with Transports" section below.
Instantiating your own Logger
If you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself:
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
You can work with this logger in the same way that you work with the default logger:
logger.log('info', 'Hello distributed log files!');
logger.info('Hello again distributed logs');
logger.add(winston.transports.File)
.remove(winston.transports.Console);
Using Logging Levels
Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger.
logger.log('info', '127.0.0.1 - there's no place like home');
logger.info('127.0.0.1 - there's no place like home');
winston.log('info', '127.0.0.1 - there's no place like home');
winston.info('127.0.0.1 - there's no place like home');
As of 0.2.0, winston supports customizable logging levels, defaulting to npm style logging levels. Changing logging levels is easy:
winston.setLevels(winston.config.syslog.levels);
logger.setLevels(winston.config.syslog.levels);
Calling .setLevels
on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels:
logger.silly('some silly message');
Using Custom Logging Levels
In addition to the predefined npm
and syslog
levels available in Winston, you can also choose to define your own:
var myCustomLevels = {
levels: {
foo: 0,
bar: 1,
baz: 2,
foobar: 3
},
colors: {
foo: 'blue',
bar: 'green',
baz: 'yellow',
foobar: 'red'
}
};
var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels });
customLevelLogger.foobar('some foobar level-ed message');
Although there is slight repetition in this data structure, it enables simple encapsulation if you not to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them:
winston.addColors(myCustomLevels.colors);
This enables transports with the 'colorize' option set to appropriately color the output of custom levels.
Events and Callbacks in Winston
Each instance of winston.Logger is also an instance of an EventEmitter. A log event will be raised each time a transport successfully logs a message:
logger.on('log', function (transport, level, msg, meta) {
});
logger.info('CHILL WINSTON!', { seriously: true });
It is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions:
logger.on('error', function (err) { });
logger.emitErrs = false;
Every logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message.
logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) {
});
Logging with Metadata
In addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple:
winston.log('info', 'Test Log Message', { anything: 'This is metadata' });
The way these objects is stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata:
- Console: Logged via util.inspect(meta)
- File: Logged via util.inspect(meta)
- Loggly: Logged in suggested Loggly format
Profiling with Winston
In addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger:
winston.profile('test');
setTimeout(function () {
winston.profile('test');
}, 1000);
All profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues.
Using winston in a CLI tool
A common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the require-analyzer written by Nodejitsu:
info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer
info: Found existing dependencies
data: {
data: colors: '0.x.x',
data: eyes: '0.1.x',
data: findit: '0.0.x',
data: npm: '1.0.x',
data: optimist: '0.2.x',
data: semver: '1.0.x',
data: winston: '0.2.x'
data: }
info: Analyzing dependencies...
info: Done analyzing raw dependencies
info: Retrieved packages from npm
warn: No additional dependencies found
Configuring output for this style is easy, just use the .cli()
method on winston
or an instance of winston.Logger
:
var winston = require('winston');
winston.cli();
var logger = new winston.Logger({
transports: [
new (winston.transports.Console)()
]
});
logger.cli();
Extending another object with Logging functionality
Often in a given code base with lots of Loggers it is useful to add logging methods a different object so that these methods can be called with less syntax. Winston exposes this functionality via the 'extend' method:
var myObject = {};
logger.extend(myObject);
myObject.info('127.0.0.1 - there's no place like home');
Working with Transports
Right now there are four transports supported by winston core. If you have a transport you would like to add either open an issue or fork and submit a pull request. Commits are welcome, but I'll give you extra street cred if you add tests too :D
- Console: Output to the terminal
- Files: Append to a file
- Loggly: Log to Logging-as-a-Service platform Loggly
Console Transport
winston.add(winston.transports.Console, options)
The Console transport takes two simple options:
- level: Level of messages that this transport should log.
- silent: Boolean flag indicating whether to suppress output
- colorize: Boolean flag indicating if we should colorize output.
Metadata: Logged via util.inspect(meta);
File Transport
winston.add(winston.transports.File, options)
The File transport should really be the 'Stream' transport since it will accept any WritableStream. It is named such because it will also accept filenames via the 'filename' option:
- level: Level of messages that this transport should log.
- silent: Boolean flag indicating whether to suppress output.
- colorize: Boolean flag indicating if we should colorize output.
- filename: The filename of the logfile to write output to.
- stream: The WriteableStream to write output to.
Metadata: Logged via util.inspect(meta);
Loggly Transport
winston.add(winston.transports.Loggly, options);
The Loggly transport is based on Nodejitsu's node-loggly implementation of the Loggly API. If you haven't heard of Loggly before, you should probably read their value proposition. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required:
- level: Level of messages that this transport should log.
- subdomain: The subdomain of your Loggly account. [required]
- auth: The authentication information for your Loggly account. [required with inputName]
- inputName: The name of the input this instance should log to.
- inputToken: The input token of the input this instance should log to.
Metadata: Logged in suggested Loggly format
MongoDB Transport
winston.add(winston.transports.MongoDB, options);
The MongoDB transport takes the following options. 'db' is required:
- level: Level of messages that this transport should log.
- silent: Boolean flag indicating whether to suppress output.
- db: The name of the database you want to log to. [required]
- collection: The name of the collection you want to store log messages in, defaults to 'log'.
- safe: Boolean indicating if you want eventual consistency on your log messages, if set to true it requires an extra round trip to the server to ensure the write was committed, defaults to true.
- host: The host running MongoDB, defaults to localhost.
- port: The port on the host that MongoDB is running on, defaults to MongoDB's default port.
Metadata: Logged as a native JSON object.
Adding Custom Transports
Adding a custom transport (say for one of the datastore on the Roadmap) is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston.
var winston = require('winston');
var CustomLogger = winston.transports.CustomerLogger = function (options) {
this.name = 'customLogger';
this.level = options.level || 'info';
};
CustomLogger.prototype.log = function (level, msg, meta, callback) {
callback(null, true);
};
What's Next?
Winston is stable and under active development. It is supported by and used at Nodejitsu.
Inspirations
- npm
- log.js
- socket.io
- node-rlog
- BigBrother
- Loggly
Road Map
- Graylog2 format support.
- Improve support for adding custom Transports not defined in Winston core.
- Create API for reading from logs across all transports.
- Add more transports: CouchDB, Redis
Run Tests
All of the winston tests are written in vows, and cover all of the use cases described above. You will need to add valid credentials for the various transports included to test/test-config.json before running tests:
{
"transports": {
"loggly": {
"subdomain": "your-subdomain",
"inputToken": "really-long-token-you-got-from-loggly",
"auth": {
"username": "your-username",
"password": "your-password"
}
}
}
}
Once you have valid configuration and credentials you can run tests with vows:
vows test/*-test.js --spec