wide
A multi-transport async logging library for node.js. Forked from winston
Motivation
Wide 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 wide 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.
Installation
npm install wide
Usage
There are two different ways to use wide: 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
- Transports
- Profiling
- Streaming Logs
- Querying Logs
- Exceptions
- Logging Levels
- Further Reading
- Working with transports
- Installation
- Run Tests
Logging
Using the Default Logger
The default logger is accessible through the wide module directly. Any method that you could call on an instance of a logger is available on the default logger:
var wide = ;wide;wide;
By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods:
wide;wide;
For more documentation about working with each individual transport supported by Wide 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 wideLoggertransports:new widetransportsConsolenew widetransportsFile filename: 'somefile.log';
You can work with this logger in the same way that you work with the default logger:
//// Logging//logger;logger;//// Adding / Removing Transports// (Yes It's chainable)//logger;
Logging with Metadata
In addition to logging string messages, wide will also optionally log additional JSON metadata objects. Adding metadata is simple:
wide;
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(data)
- File: Logged via util.inspect(data)
Profiling
In addition to logging messages and metadata, wide also has a simple profiling mechanism implemented for any logger:
//// Start profile of 'test'// Remark: Consider using Date.now() with async operations//wideprofile'test';;
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.
String interpolation
The log
method provides the same string interpolation methods like [util.format
][10].
This allows for the following log messages.
logger;// info: test message my stringlogger;// info: test message 123logger;// info: test message {"number":123}// data = {}logger;// info: test message first, second// data = {number: 123}logger;// info: test message first second// data = {number: 123}logger;// info: test message first, second// data = {numer: 123}// callback = function(){}logger;// info: test message first second// data = {numer: 123}// callback = function(){}
Querying Logs
Wide supports querying of logs with Loggly-like options. See Loggly Search API.
Specifically: File
, Couchdb
, Redis
, Loggly
, Nssocket
, and Http
.
var options =from: - 24 * 60 * 60 * 1000until:limit: 10start: 0order: 'desc'fields: 'message';//// Find items logged between today and yesterday.//wide;
Streaming Logs
Streaming allows you to stream your logs back from your chosen transport.
//// Start at the end.//wide;
Exceptions
Handling Uncaught Exceptions with wide
With wide
, 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 wide logger or your own logger instance.
If you want to use this feature with the default logger simply call .handleExceptions()
with a transport instance.
//// You can add a separate exception logger by passing it to `.handleExceptions`//wide//// Alternatively you can set `.handleExceptions` to true when adding transports to wide//wide;
To Exit or Not to Exit
By default, wide will exit after logging an uncaughtException. if this is not the behavior you want,
set exitOnError = false
var logger = new wideLogger exitOnError: false ;//// or, like this://loggerexitOnError = 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 wideLoggertransports:filename: 'path/to/all-logs.log'exceptionHandlers:filename: 'path/to/exceptions.log';
Example 2
var logger = new wide.Logger({
transports: [
new wide.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:
{return errcode !== 'EPIPE';}var logger = new wideLogger exitOnError: ignoreEpipe ;//// or, like this://loggerexitOnError = ignoreEpipe;
Logging Levels
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 wide Logger.
//// Any logger instance//logger;logger;logger;logger;logger;logger;logger;logger;logger;//// Default logger//wide;wide;
Wide allows you to set a level
on each transport that specifies the level of messages this transport should log. For example, you could log only errors to the console, with the full logs in a file (note that the default level of a transport is info
):
var logger = new wideLoggertransports:new widetransportsConsole level: 'error'new widetransportsFile filename: 'somefile.log';
You may also dynamically change the log level of a transport:
var logger = new wideLoggertransports:new widetransportsConsole level: 'warn'new widetransportsFile filename: 'somefile.log' level: 'error';logger;loggertransportsconsolelevel = 'debug';loggertransportsfilelevel = 'verbose';logger;
As of 0.2.0, wide supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy:
//// Change levels on the default wide logger//wide;//// Change levels on an instance of a logger//logger;
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 does not have 'silly' defined since that level is not in the syslog levels//logger;
Using Custom Logging Levels
In addition to the predefined npm
and syslog
levels available in Wide, you can also choose to define your own:
var myCustomLevels =levels:foo: 0bar: 1baz: 2foobar: 3colors:foo: 'blue'bar: 'green'baz: 'yellow'foobar: 'red';var customLevelLogger = new wideLogger levels: myCustomLevelslevels ;customLevelLogger;
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 wide aware of them:
//// Make wide aware of these colors//wide;
This enables transports with the 'colorize' option set to appropriately color the output of custom levels.
Further Reading
Events and Callbacks in Wide
Each instance of wide.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message:
logger;logger;
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:
//// Handle errors//logger;//// Or just suppress them.//loggeremitErrs = 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;
Working with multiple Loggers in wide
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 wide
in two ways: through wide.loggers
and instances of wide.Container
. In fact, wide.loggers
is just a predefined instance of wide.Container
:
var wide = ;//// Configure the logger for `category1`//wideloggers;//// Configure the logger for `category2`//wideloggers;
Now that your loggers are setup you can require wide in any file in your application and access these pre-configured loggers:
var wide = ;//// Grab your preconfigured logger//var category1 = wideloggers;category1;
If you prefer to manage the Container
yourself you can simply instantiate one:
var wide =container = ;container;
Sharing transports between Loggers in wide
var wide = ;//// Setup transports to be shared across all loggers// in three ways://// 1. By setting it on the default Container// 2. By passing `transports` into the constructor function of wide.Container// 3. By passing `transports` into the `.get()` or `.add()` methods////// 1. By setting it on the default Container//wideloggersoptionstransports =// Setup your shared transports here;//// 2. By passing `transports` into the constructor function of wide.Container//var container =transports:// Setup your shared transports here;//// 3. By passing `transports` into the `.get()` or `.add()` methods//wideloggers;container;
Using wide in a CLI tool
A common use-case for logging is output to a CLI tool. Wide 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: wide: '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 wide
or an instance of wide.Logger
:
var wide = ;//// Configure CLI output on the default logger//wide;//// Configure CLI on an instance of wide.Logger//var logger =transports:new widetransportsConsole;logger;
Extending another object with Logging
Often in a given code base with lots of Loggers it is useful to add logging methods to a different object so that these methods can be called with less syntax. Wide exposes this functionality via the 'extend' method:
var myObject = {};logger;//// You can now call logger methods on 'myObject'//myObject;
Working with Transports
There are many transports supported by wide 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 Transport
wide
The Console transport takes a few simple options:
- level: Level of messages that this transport should log (default 'info').
- silent: Boolean flag indicating whether to suppress output (default false).
- colorize: Boolean flag indicating if we should colorize output (default false).
- timestamp: Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.
Metadata: Logged via util.inspect(data);
File Transport
wide
The File transport should really be the 'Stream' transport since it will accept any [WritableStream][14]. 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.
- timestamp: Boolean flag indicating if we should prepend output with timestamps (default true). If function is specified, its return value will be used instead of timestamps.
- filename: The filename of the logfile to write output to.
- maxsize: Max size in bytes of the logfile, if the size is exceeded then a new file is created.
- maxFiles: Limit the number of files created when the size of the logfile is exceeded.
- stream: The WriteableStream to write output to.
- json: If true, messages will be logged as JSON (default true).
- logstash: If true, messages will be logged as JSON and formatted for logstash (default false).
Metadata: Logged via util.inspect(data);
Loggly Transport
var Loggly = Logglywide;
The Loggly transport is based on [Nodejitsu's][3] [node-loggly][6] implementation of the [Loggly][7] API. If you haven't heard of Loggly before, you should probably read their [value proposition][8]. 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.
- json: If true, messages will be sent to Loggly as JSON.
Metadata: Logged in suggested [Loggly format][2]
Riak Transport
As of 0.3.0
the Riak transport has been broken out into a new module: [wide-riak][17]. Using it is just as easy:
var Riak = Riak;wide;
In addition to the options accepted by the [riak-js][3] [client][4], the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to false by default:
- level: Level of messages that this transport should log.
- bucket: The name of the Riak bucket you wish your logs to be in or a function to generate bucket names dynamically.
// Use a single bucket for all your logsvar singleBucketTransport = new Riak bucket: 'some-logs-go-here' ;// Generate a dynamic bucket based on the date and levelvar dynamicBucketTransport = new Riak{var d = now;return level + d d d;};
Metadata: Logged as JSON literal in Riak
MongoDB Transport
As of 0.3.0
the MongoDB transport has been broken out into a new module: [wide-mongodb][16]. Using it is just as easy:
var MongoDB = MongoDB;wide;
For more information about its arguments, check [wide-mongodb's README][16].
SimpleDB Transport
The [wide-simpledb][18] transport is just as easy:
var SimpleDB = SimpleDB;wide;
The SimpleDB transport takes the following options. All items marked with an asterisk are required:
- awsAccessKey:* your AWS Access Key
- secretAccessKey:* your AWS Secret Access Key
- awsAccountId:* your AWS Account Id
- domainName:* a string or function that returns the domain name to log to
- region:* the region your domain resides in
- itemName: a string ('uuid', 'epoch', 'timestamp') or function that returns the item name to log
Metadata: Logged as a native JSON object to the 'data' attribute of the item.
Mail Transport
The [wide-mail][19] is an email transport:
var Mail = Mail;wide;
The Mail transport uses emailjs behind the scenes. Options are the following:
- to: The address(es) you want to send to. [required]
- from: The address you want to send from. (default:
wide@[server-host-name]
) - host: SMTP server hostname (default: localhost)
- port: SMTP port (default: 587 or 25)
- username User for server auth
- password Password for server auth
- ssl: Use SSL (boolean or object { key, ca, cert })
- tls: Boolean (if true, use starttls)
- level: Level of messages that this transport should log.
- silent: Boolean flag indicating whether to suppress output.
Metadata: Stringified as JSON in email.
Amazon SNS (Simple Notification System) Transport
The [wide-sns][21] transport uses amazon SNS to send emails, texts, or a bunch of other notifications.
SNS;wide;
Options:
- aws_key: Your Amazon Web Services Key. [required]
- aws_secret: Your Amazon Web Services Secret. [required]
- subscriber: Subscriber number - found in your SNS AWS Console, after clicking on a topic. Same as AWS Account ID. [required]
- topic_arn: Also found in SNS AWS Console - listed under a topic as Topic ARN. [required]
- region: AWS Region to use. Can be one of:
us-east-1
,us-west-1
,eu-west-1
,ap-southeast-1
,ap-northeast-1
,us-gov-west-1
,sa-east-1
. (default:us-east-1
) - subject: Subject for notifications. (default: "Wide Error Report")
- message: Message of notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: "Level '%l' Error:\n%e\n\nMetadata:\n%m")
- level: lowest level this transport will log. (default:
info
)
Graylog2 Transport
[wide-graylog2][22] is a Graylog2 transport:
var Graylog2 = Graylog2;wide;
The Graylog2 transport connects to a Graylog2 server over UDP using the following options:
-
level: Level of messages this transport should log. (default: info)
-
silent: Boolean flag indicating whether to suppress output. (default: false)
-
graylogHost: IP address or hostname of the graylog2 server. (default: localhost)
-
graylogPort: Port to send messages to on the graylog2 server. (default: 12201)
-
graylogHostname: The hostname associated with graylog2 messages. (default: require('os').hostname())
-
graylogFacility: The graylog2 facility to send log messages.. (default: nodejs)
Metadata: Stringified as JSON in the full message GELF field.
Papertrail Transport
[wide-papertrail][23] is a Papertrail transport:
var Papertrail = Papertrail;wide;
The Papertrail transport connects to a PapertrailApp log destination over TCP (TLS) using the following options:
- level: Level of messages this transport should log. (default: info)
- host: FQDN or IP address of the Papertrail endpoint.
- port: Port for the Papertrail log destination.
- hostname: The hostname associated with messages. (default: require('os').hostname())
- program: The facility to send log messages.. (default: default)
- logFormat: a log formatting function with the signature
function(level, message)
, which allows custom formatting of the level or message prior to delivery
Metadata: Logged as a native JSON object to the 'data' attribute of the item.
Cassandra Transport
[wide-cassandra][24] is a Cassandra transport:
var Cassandra = Cassandra;wide;
The Cassandra transport connects to a cluster using the native protocol with the following options:
- level: Level of messages that this transport should log (default:
'info'
). - table: The name of the Cassandra column family you want to store log messages in (default:
'logs'
). - partitionBy: How you want the logs to be partitioned. Possible values
'hour'
and'day'
(Default). - consistency: The consistency of the insert query (default:
quorum
).
In addition to the options accepted by the Node.js Cassandra driver Client.
- hosts: Cluster nodes that will handle the write requests:
Array of strings containing the hosts, for example
['host1', 'host2']
(required). - keyspace: The name of the keyspace that will contain the logs table (required). The keyspace should be already created in the cluster.
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 wide.
var util =wide = ;var CustomLogger = widetransports {//// Name this logger//thisname = 'customLogger';//// Set the level from your options//thislevel = optionslevel || 'info';//// Configure your storage backing as you see fit//};//// Inherit from `wide.Transport` so you can take advantage// of the base functionality and `.handleExceptions()`.//util;CustomLoggerprototype {//// Store this message and metadata, maybe use some custom logic// then callback indicating success.//;};
Inspirations
- [npm][0]
- [log.js][4]
- [socket.io][5]
- [node-rlog][6]
- [BigBrother][7]
- [Loggly][8]
Installation
Installing npm (node package manager)
curl http://npmjs.org/install.sh | sh
Installing wide
[sudo] npm install wide
Run Tests
All of the wide tests are written in [vows][9], and designed to be run with npm.
$ npm test