winston
A multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs."
Installation
npm install @e7/winston
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.
Logging
Logging levels in winston
conform to the severity ordering specified by RFC5424: severity of all levels is assumed to be numerically ascending from most important to least important.
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');
winston.level = 'debug';
winston.log('debug', 'Now my debug messages are written to console!');
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);
Or do it with one call to configure():
winston.configure({
transports: [
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
For more documentation about working with each individual transport supported by Winston see the Winston Transports document.
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);
You can also wholesale reconfigure a winston.Logger
instance using the configure
method:
var logger = new winston.Logger({
level: 'info',
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
logger.configure({
level: 'verbose',
transports: [
new (require('winston-daily-rotate-file'))(opts)
]
});
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 are 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)
Multiple transports of the same type
It is possible to use multiple transports of the same type e.g. winston.transports.File
by passing in a custom name
when you construct the transport.
var logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
name: 'info-file',
filename: 'filelog-info.log',
level: 'info'
}),
new (winston.transports.File)({
name: 'error-file',
filename: 'filelog-error.log',
level: 'error'
})
]
});
If you later want to remove one of these transports you can do so by using the string name. e.g.:
logger.remove('info-file');
In this example, one could also remove by passing in the instance of the Transport itself. e.g. this is equivalent to the string example above:
var infoFile = logger.transports[0];
logger.remove(infoFile);
Profiling
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);
Also you can start a timer and keep a reference that you can call .done() on
var timer = winston.startTimer()
setTimeout(function(){
timer.done("Logging message");
}, 1000);
All profile messages are set to 'info' level 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.
String interpolation
The log
method provides the same string interpolation methods like [util.format
][10].
This allows for the following log messages.
logger.log('info', 'test message %s', 'my string');
logger.log('info', 'test message %d', 123);
logger.log('info', 'test message %j', {number: 123}, {});
logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123});
logger.log('info', 'test message', 'first', 'second', {number: 123});
logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123}, function(){});
logger.log('info', 'test message', 'first', 'second', {number: 123}, function(){});
Querying Logs
Winston supports querying of logs with Loggly-like options. See Loggly Search API.
Specifically: File
, Couchdb
, Redis
, Loggly
, Nssocket
, and Http
.
var options = {
from: new Date - 24 * 60 * 60 * 1000,
until: new Date,
limit: 10,
start: 0,
order: 'desc',
fields: ['message']
};
winston.query(options, function (err, results) {
if (err) {
throw err;
}
console.log(results);
});
Streaming Logs
Streaming allows you to stream your logs back from your chosen transport.
winston.stream({ start: -1 }).on('log', function(log) {
console.log(log);
});
Exceptions
Handling Uncaught Exceptions with winston
With winston
, it is possible to catch and log uncaughtException
events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance.
If you want to use this feature with the default logger, simply call .handleExceptions()
with a transport instance.
winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' }));
winston.add(winston.transports.File, {
filename: 'path/to/all-logs.log',
handleExceptions: true,
humanReadableUnhandledException: true
});
winston.handleExceptions([ transport1, transport2, ... ]);
To Exit or Not to Exit
By default, winston will exit after logging an uncaughtException. If this is not the behavior you want,
set exitOnError = false
var logger = new (winston.Logger)({ exitOnError: false });
logger.exitOnError = false;
When working with custom logger instances, you can pass in separate transports to the exceptionHandlers
property or set .handleExceptions
on any transport.
Example 1
var logger = new (winston.Logger)({
transports: [
new winston.transports.File({ filename: 'path/to/all-logs.log' })
],
exceptionHandlers: [
new winston.transports.File({ filename: 'path/to/exceptions.log' })
]
});
Example 2
var logger = new winston.Logger({
transports: [
new winston.transports.Console({
handleExceptions: true,
json: true
})
],
exitOnError: false
});
The exitOnError
option can also be a function to prevent exit on only certain types of errors:
function ignoreEpipe(err) {
return err.code !== 'EPIPE';
}
var logger = new (winston.Logger)({ exitOnError: ignoreEpipe });
logger.exitOnError = ignoreEpipe;
Logging Levels
Each level
is given a specific integer priority. The higher the priority the more important the message is considered to be, and the lower the corresponding integer priority. For example, npm
logging levels are prioritized from 0 to 5 (highest to lowest):
{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }
Similarly, as specified exactly in RFC5424 the syslog
levels are prioritized from 0 to 7 (highest to lowest).
{ emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 }
If you do not explicitly define the levels that winston
should use the npm
levels above will be used.
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('silly', "127.0.0.1 - there's no place like home");
logger.log('debug', "127.0.0.1 - there's no place like home");
logger.log('verbose', "127.0.0.1 - there's no place like home");
logger.log('info', "127.0.0.1 - there's no place like home");
logger.log('warn', "127.0.0.1 - there's no place like home");
logger.log('error', "127.0.0.1 - there's no place like home");
logger.info("127.0.0.1 - there's no place like home");
logger.warn("127.0.0.1 - there's no place like home");
logger.error("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");
winston
allows you to define a level
property on each transport which specifies the maximum level of messages that a transport should log. For example, using the npm
levels you could log only error
messages to the console and everything info
and below to a file (which includes error
messages):
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'error' }),
new (winston.transports.File)({
filename: 'somefile.log',
level: 'info'
})
]
});
You may also dynamically change the log level of a transport:
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'warn' }),
new (winston.transports.File)({ filename: 'somefile.log', level: 'error' })
]
});
logger.debug("Will not be logged in either transport!");
logger.transports.console.level = 'debug';
logger.transports.file.level = 'verbose';
logger.verbose("Will be logged in both transports!");
As of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] 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 do not want 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.
Further Reading
Events and Callbacks in Winston
Each instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message:
logger.on('logging', 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) {
});
Working with multiple Loggers in winston
Often in larger, more complex, applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in winston
in two ways: through winston.loggers
and instances of winston.Container
. In fact, winston.loggers
is just a predefined instance of winston.Container
:
var winston = require('winston');
winston.loggers.add('category1', {
console: {
level: 'silly',
colorize: true,
label: 'category one'
},
file: {
filename: '/path/to/some/file'
}
});
winston.loggers.add('category2', {
couchdb: {
host: '127.0.0.1',
port: 5984
}
});
Now that your loggers are setup, you can require winston in any file in your application and access these pre-configured loggers:
var winston = require('winston');
var category1 = winston.loggers.get('category1');
category1.info('logging from your IoC container-based logger');
If you prefer to manage the Container
yourself, you can simply instantiate one:
var winston = require('winston'),
container = new winston.Container();
container.add('category1', {
console: {
level: 'silly',
colorize: true
},
file: {
filename: '/path/to/some/file'
}
});
Sharing transports between Loggers in winston
var winston = require('winston');
winston.loggers.options.transports = [
];
var container = new winston.Container({
transports: [
]
});
winston.loggers.add('some-category', {
transports: [
]
});
container.add('some-category', {
transports: [
]
});
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][2] written by [Nodejitsu][3]:
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();
Filters and Rewriters
Filters allow modifying the contents of log messages, and Rewriters allow modifying the contents of log meta e.g. to mask data that should not appear in logs.
Both filters and rewriters are simple Arrays of functions which can be provided when creating a new winston.Logger(options)
. e.g.:
var logger = new winston.Logger({
rewriters: [function (level, msg, meta) { }],
filters: [function (level, msg, meta) { }]
})
Like any Array, they can also be modified at runtime with no adverse side-effects to the winston
internals.
logger.filters.push(function(level, msg, meta) {
return meta.production
? maskCardNumbers(msg)
: msg;
});
logger.info('transaction with card number 123456789012345 successful.');
This may result in this output:
info: transaction with card number 123456****2345 successful.
Where as for rewriters, if you wanted to sanitize the creditCard
field of your meta
you could:
logger.rewriters.push(function(level, msg, meta) {
if (meta.creditCard) {
meta.creditCard = maskCardNumbers(meta.creditCard)
}
return meta;
});
logger.info('transaction ok', { creditCard: 123456789012345 });
which may result in this output:
info: transaction ok creditCard=123456****2345
See log-filter-test.js, where card number masking is implemented as an example along with log-rewriter-test.js
Adding Custom Transports
Adding a custom transport 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 util = require('util'),
winston = require('winston');
var CustomLogger = winston.transports.CustomLogger = function (options) {
this.name = 'customLogger';
this.level = options.level || 'info';
};
util.inherits(CustomLogger, winston.Transport);
CustomLogger.prototype.log = function (level, msg, meta, callback) {
callback(null, true);
};
Custom Log Format
To specify a custom log format for a transport, you should set a formatter function. Currently supported transports are: Console, File, Memory.
An options object will be passed to the formatter function. Its general properties are: timestamp, level, message, meta. Depending on the transport type, there may be additional properties.
var config = winston.config;
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
timestamp: function() {
return Date.now();
},
formatter: function(options) {
return options.timestamp() + ' ' +
config.colorize(options.level, options.level.toUpperCase()) + ' ' +
(options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
}
})
]
});
logger.info('Data to log.');
Inspirations
- [npm][0]
- [log.js][4]
- [socket.io][5]
- [node-rlog][6]
- [BigBrother][7]
- [Loggly][8]
Installation
Installing npm (node package manager)
curl https://npmjs.org/install.sh | sh
Installing winston
[sudo] npm install winston
Run Tests
All of the winston tests are written in [vows][9], and designed to be run with npm.
$ npm test