Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cli-logger

Package Overview
Dependencies
Maintainers
1
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cli-logger - npm Package Compare versions

Comparing version 0.4.2 to 0.5.1

lib/console-stream.js

90

index.js

@@ -1,2 +0,2 @@

var events = require('events');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');

@@ -15,2 +15,3 @@ var os = require('os');

var FILE = 'file';
var CONSOLE = 'console';

@@ -39,3 +40,3 @@ var LEVELS = {

var keys = Object.keys(LEVELS); keys.pop();
var types = [RAW, STREAM, FILE];
var types = [RAW, STREAM, FILE, CONSOLE];
var defaults = {

@@ -45,2 +46,4 @@ name: basename(process.argv[1]),

src: false,
hostname: null,
pid: null,
stack: false,

@@ -67,4 +70,5 @@ console: false,

var Logger = function(conf, bitwise, parent) {
events.EventEmitter.call(this);
EventEmitter.call(this);
conf = conf || {};
this.keys = keys;
this.bitwise = (bitwise === true);

@@ -74,5 +78,3 @@ this.configure();

var streams = conf.streams, stream = conf.stream;
streams = streams || {
stream: stream || process.stdout
}
streams = streams || this.getDefaultStream(conf);
delete conf.streams;

@@ -90,19 +92,2 @@ delete conf.stream;

this.hostname = this.conf.hostname || os.hostname();
if(this.conf.console) {
var writers = this.conf.writers || {};
if(typeof writers === 'function') {
var writer = writers;
writers = {};
keys.forEach(function(method) {
writers[method] = writer;
})
}
this.writers = {};
this.writers[LEVELS.trace] = writers.trace || console.log;
this.writers[LEVELS.debug] = writers.debug || console.log;
this.writers[LEVELS.info] = writers.info || console.info;
this.writers[LEVELS.warn] = writers.warn || console.warn;
this.writers[LEVELS.error] = writers.error || console.error;
this.writers[LEVELS.fatal] = writers.fatal || console.error;
}
this.fields = {};

@@ -117,5 +102,20 @@ this.streams = [];

util.inherits(Logger, events.EventEmitter);
util.inherits(Logger, EventEmitter);
/**
* Retrieve the default stream when no streams have been configured.
*
* @param conf The configuration object.
*/
Logger.prototype.getDefaultStream = function(conf) {
var stream = conf.stream;
if(conf.console && !(stream instanceof ConsoleStream)) {
stream = new ConsoleStream({writers: conf.writers});
}
return {
stream: stream || process.stdout
}
}
/**
* Configure instance log levels.

@@ -240,5 +240,4 @@ *

}
if(source.stream && !(source.stream instanceof Writable)
&& source.stream !== process.stdout
&& source.stream !== process.stderr) {
if(source.stream && !(source.stream instanceof EventEmitter)
&& typeof source.stream.write !== 'function') {
throw new Error('Invalid stream specified');

@@ -248,3 +247,8 @@ }

source.type = RAW;
}else if((source.stream instanceof ConsoleStream)) {
source.type = CONSOLE;
}
if(source.stream && typeof source.stream.logger === 'function') {
source.stream.logger(this);
}
this.append(source);

@@ -385,7 +389,5 @@ }

var msg = '' + record.msg;
if(!this.conf.console && parameters) {
params = parameters.slice(0);
params.unshift(record.msg);
record.msg = util.format.apply(util, params);
}
params = parameters.slice(0);
params.unshift(record.msg);
record.msg = util.format.apply(util, params);
if(typeof this.conf.prefix === 'function') {

@@ -406,13 +408,12 @@ record.msg = this.conf.prefix.apply(this, [record]) + record.msg;

event = record;
if(this.conf.console && this.writers[level]) {
this.writers[level].apply(
console, [record.msg].concat(parameters));
if(target.type === CONSOLE) {
record.message = msg;
record.parameters = parameters;
target.stream.write(record);
}else if(typeof json === 'string') {
target.stream.write(json + '\n');
}else if(target.type === RAW){
target.stream.write(record);
}else{
if(typeof json === 'string') {
target.stream.write(json + '\n');
}else if(target.type === RAW){
target.stream.write(record);
}else{
target.stream.write(record.msg + '\n');
}
target.stream.write(record.msg + '\n');
}

@@ -425,3 +426,3 @@ }

}
return (listeners.length === 0);
return (listeners.length === 0 && event !== undefined);
}

@@ -685,2 +686,3 @@

var ConsoleStream = require('./lib/console-stream');
var RingBuffer = require('./lib/ring-buffer');

@@ -724,2 +726,3 @@ var serializers = require('./lib/serializers');

module.exports.Logger = Logger;
module.exports.ConsoleStream = ConsoleStream;
module.exports.RingBuffer = RingBuffer;

@@ -735,2 +738,3 @@ for(z in LEVELS) {

module.exports.FILE = FILE;
module.exports.CONSOLE = CONSOLE;
module.exports.LOG_VERSION = major;

@@ -0,4 +1,4 @@

var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var util = require('util');
var Writable = require('stream').Writable;
var circular = require('./circular');

@@ -12,3 +12,3 @@

var RingBuffer = function(options) {
Writable.apply(this, arguments);
EventEmitter.apply(this, arguments);
options = options || {};

@@ -20,3 +20,3 @@ this.limit = options.limit || 16;

util.inherits(RingBuffer, Writable);
util.inherits(RingBuffer, EventEmitter);

@@ -26,11 +26,5 @@ /**

*
* @param chunk The buffer or string to write, will
* be coerced to a string.
* @param record The log record.
*/
RingBuffer.prototype.write = function(chunk) {
var record = chunk;
if((chunk instanceof Buffer) || typeof chunk === 'string') {
record = '' + chunk;
record = record.replace(/\s+$/, '');
}
RingBuffer.prototype.write = function(record) {
this.records.push(record);

@@ -37,0 +31,0 @@ if(this.records.length > this.limit) {

{
"name": "cli-logger",
"version": "0.4.2",
"version": "0.5.1",
"description": "Logger implementation for command line interfaces",

@@ -5,0 +5,0 @@ "author": "muji <noop@xpm.io>",

@@ -5,2 +5,6 @@ # Logger

This module is inspired by and borrows from [bunyan][bunyan] it differs primarily in that it is designed for command line interfaces rather than long running services. For all intents and purposes it is a drop in replacement for [bunyan][bunyan], see [credits](#credits) for more information.
The library is considered feature complete and ready for use, however the major version has not been incremented to `1` to maintain compatibility with [bunyan][bunyan].
## Install

@@ -93,19 +97,18 @@

In normal mode the additional constant `NONE` (70) may be used to disable logging. In bitwise mode you may also use `BW_NONE` (0) and `BW_ALL` (63), `BW_ALL` is particularly useful for `XOR` operations.
In normal mode the additional constant `NONE` (70) may be used to disable logging. In bitwise mode you may also use `BW_NONE` (0) and `BW_ALL` (63), `BW_ALL` is particularly useful for `XOR` operations, see [constants](#constants).
The API for getting and setting log levels is consistent with [bunyan][bunyan]:
The API for getting and setting log levels is identical to [bunyan][bunyan]:
```javascript
log.info() // true if any stream is enabled for the info level
log.level() // get a level integer (lowest level of all streams)
log.level(INFO) // sets all streams to the INFO level
log.level('info') // sets all streams to the INFO level (normal only)
log.level(BW_INFO) // sets all streams to the INFO level (bitwise only)
log.levels() // gets an array of the levels of all streams
log.levels(0) // get level of stream at index zero
log.levels('foo') // get level of the stream named 'foo'
log.levels(0, INFO) // set level of stream at index zero to INFO
log.levels(0, 'info') // set level of stream at index zero to INFO (normal only)
log.levels(0, BW_INFO) // set level of stream at index zero to INFO (bitwise only)
log.levels('foo', WARN) // set level of stream named 'foo' to WARN
log.info() // true if any stream is enabled for the info level
log.level() // get a level integer (lowest level of all streams)
log.level(log.INFO) // sets all streams to the INFO level
log.level('info') // sets all streams to the INFO level (normal)
log.levels() // gets an array of the levels of all streams
log.levels(0) // get level of stream at index zero
log.levels('foo') // get level of the stream named 'foo'
log.levels(0, log.INFO) // set level of stream at index zero to INFO
log.levels(0, 'info') // set level of stream at index zero to INFO (normal)
log.levels(0, log.INFO) // set level of stream at index zero to INFO
log.levels('foo', log.WARN) // set level of stream named 'foo' to WARN
```

@@ -116,5 +119,7 @@

* `console`: A boolean indicating that console methods should be used when writing log records, this enables the [ttycolor][ttycolor] integration, default is `false`, see [console](#console).
* `hostname`: Allows overriding the `hostname` field added to all log records, default is `null` but is automatically set to `os.hostname()` if not specified, see [record](#record).
* `json`: Print log records as newline delimited JSON, default is `false`, see [json](#json).
* `level`: A default log level to use when a stream does not explicitly specify a log level, default is `INFO`, see [level](#level).
* `name`: The name of the logger, default is `basename(process.argv[1])`, see [name](#name).
* `pid`: Allows overriding the `pid` field added to all log records, default is `null` but is automatically set to `process.pid` if not specified, see [record](#record).
* `prefix`: A function used to prepend a prefix to log messages, default is `null`, see [prefix](#prefix).

@@ -292,2 +297,11 @@ * `serializers`: Map of log record property names to serialization functions,

The following types of streams are supported:
* `stream`: An existing stream such as `process.stdout`, `process.stderr` or some other writable stream.
* `file`: Creates a writable stream from a string file system path.
* `raw`: Forces the raw log record to always be passed to the `write()` method of the stream.
* `console`: A stream that writes log messages to a `console` method, streams of this type are passed the raw log record which is decorated with the additional properties `message` (the raw message string) and `parameters` (message replacement parameters).
#### Stream
Configuring output streams is typically done using an array, but as a convenience an object may be specified to configure a single output stream:

@@ -348,2 +362,415 @@

#### Raw
The raw stream type is useful when you want to ensure that the stream implementation is passed the raw log record, this type is implied when using a [ring buffer](#ring-buffer).
#### Console
Use the `console` stream type when you need access to the raw message and message replacement parameters. This stream type is implied when the `console` configuration property is set, alternatively you can use this to redirect some messages to `console` methods and possibly others to a log file as JSON records, for example:
```javascript
var logger = require('cli-logger');
var conf = {
streams: [
{
stream: new logger.ConsoleStream(),
level: log.BW_TRACE|log.BW_DEBUG|log.BW_INFO
},
{
path: 'log/json.log',
json: true,
level: log.BW_ALL^log.BW_TRACE^log.BW_DEBUG^log.BW_INFO
}
]
}
var log = logger(conf, true);
// print to stdout using `console.info`
log.info('mock %s message', 'info');
// print to log file as a json record
log.warn('mock %s message', 'warn');
```
See the [json][json] example program.
## Child Loggers
The module supports child loggers to label subcomponents of your application and follows the same rules as [bunyan][bunyan]:
* All streams are inherited from the parent logger, you may configure child loggers with additional streams but you cannot remove the streams inherited from the parent.
* The parent's serializers are inherited though may be overriden in the child.
* Changes to the log level of a child logger do not affect the parent log level.
See the [child][child] example program.
## Ring Buffer
The `RingBuffer` implementation does not write records to a stream it gathers them into an array (with a specified limit) and optionally can flush the records to a stream at a later time.
This is useful if you wish to keep track of all (or some) log messages and then write a debug log file when a particular event occurs (such as a fatal error).
See the [ringbuffer][ringbuffer] example program.
## Events
The `Logger` implementation dispatches the following events:
### error
Emitted if there is an error on an underlying stream, it is recommended you listen for this event.
```javascript
function error(err, stream)
```
### log
Emitted when a log record has been written to stream(s), if listeners exist for `write` this event will not fire.
```javascript
function log(record, level, msg, parameters)
```
Note that if a log record is written to multiple streams this event will only be emitted once for the log record.
### write
If a listener exists for this event it is invoked with all the log record information and no data is written by the logger to the underlying stream(s).
```javascript
function write(record, stream, msg, parameters)
```
Note that `record.msg` contains the message with parameters substituted, whilst `msg` and `parameters` are the raw message and replacement parameters should you need them.
This event will fire once for each stream that is enabled for the log level associated with the record and effectively disables all the default logic for writing log records, if you listen for this event it is your responsibility to process the log record.
## Constants
The exposed log level constants deserve some attention. The module exposes all normal mode levels as constants, eg `INFO` and prefixes bitwise constants for example, `BW_INFO`. However constants are also exposed on the instance regardless of mode, such that the following is possible:
```javascript
var logger = require('cli-logger');
log = logger();
// set level of all streams to warn
log.level(log.WARN);
// ...
```
The equivalent for bitwise mode is:
```javascript
var logger = require('cli-logger');
log = logger(null, true);
// set level of all streams to warn
log.level(log.WARN);
// ...
```
Note that no prefix is necessary when accessing constants on the instance.
The rule of thumb is that if you are setting log levels in the configuration then use the prefixed constants for bitwise mode. If you are setting log levels after instantiation then you can use the constants exposed by the `Logger` instance without a prefix regardless of mode.
## Record
Log record fields are consistent with [bunyan][bunyan], a log record in normal mode may look like:
```json
{
"time": "2014-02-18T06:42:41.868Z",
"pid": 31641,
"hostname": "pearl.local",
"name": "record",
"msg": "mock info message",
"level": 30,
"v": 0
}
```
See the [record][record] example program.
### Fields
* `v`: Required integer, cannot be overriden. Module major version extracted from `package.json`.
* `level`: Required integer, cannot be overriden. Determined automatically by the log method.
* `name`: Required string, cannot be overriden. Provided at creation or `basename(process.argv[1])`.
* `hostname`: Required string, provided at creation or `os.hostname()`.
* `pid`: Required integer, provided at creation or `process.pid`.
* `time`: Required string, can be overriden. Default is `new Date().toISOString()`.
* `msg`: Required string. Must be supplied when calling a log method.
* `src`: Optional object, contains log caller information. Automatically added if the `src` configuration property has been set.
You may add your own fields to log records by specifying an object as the first argument to a log method, see [messages](#messages).
## API
### Module
#### logger([conf], [bitwise])
Create a `Logger` instance.
* `conf`: A configuration for the logger.
* `bitwise`: A boolean indicating the logger uses bitwise log levels.
```javascript
var logger = require('cli-logger');
var log = logger();
```
#### createLogger([conf], [bitwise])
Create a `Logger` instance and enable JSON log records for all streams.
* `conf`: A configuration for the logger.
* `bitwise`: A boolean indicating the logger uses bitwise log levels.
```javascript
var logger = require('cli-logger');
var log = logger.createLogger();
```
#### bitwise
Map of all bitwise mode constants.
#### circular
Reference to the function used to safely `stringify` objects that may contain circular references.
#### ConsoleStream
Reference to the `ConsoleStream` class.
#### keys
Array of log method names.
#### levels
Map of all normal mode constants.
#### Logger
Reference to the `Logger` class.
#### RingBuffer
Reference to the `RingBuffer` class.
#### serializers
Map of standard serializer functions, aliased via `stdSerializers`, see [serializers](#serializers).
#### types
Array of supported stream types.
#### Constants (miscellaneous)
* `CONSOLE`: String representing the console stream type.
* `FILE`: String representing the file stream type.
* `LOG_VERSION`: Integer indicating the module major version.
* `RAW`: String representing the raw stream type.
* `STREAM`: String representing the stream type.
#### Constants (normal)
* `TRACE`: Integer representing the trace log level.
* `DEBUG`: Integer representing the debug log level.
* `INFO`: Integer representing the info log level.
* `WARN`: Integer representing the warn log level.
* `ERROR`: Integer representing the error log level.
* `FATAL`: Integer representing the fatal log level.
* `NONE`: Integer representing the none log level.
#### Constants (bitwise)
* `BW_NONE`: Integer representing the none log level.
* `BW_TRACE`: Integer representing the trace log level.
* `BW_DEBUG`: Integer representing the debug log level.
* `BW_INFO`: Integer representing the info log level.
* `BW_WARN`: Integer representing the warn log level.
* `BW_ERROR`: Integer representing the error log level.
* `BW_FATAL`: Integer representing the fatal log level.
* `BW_ALL`: Integer representing the all log level.
### ConsoleStream
Class used to redirect log records to `console` methods.
#### ConsoleStream([options])
Create a `ConsoleStream` instance.
* `options`: Options for the console stream.
The `options` may contain a `writers` property to map log level string names to `console` functions, see [writers](#writers).
### Logger
Class representing the logger implementation.
#### Logger([conf], [bitwise])
Create a `Logger` instance.
* `conf`: A configuration for the logger.
* `bitwise`: A boolean indicating the logger uses bitwise log levels.
#### child([conf], [bitwise])
Creates a child `Logger` instance, see [child loggers](#child-loggers).
* `conf`: A configuration for the child logger.
* `bitwise`: A boolean indicating the child logger uses bitwise log levels.
#### conf
Map of the logger configuration.
#### debug([object], message, ...)
Log a debug message.
* `object`: An object or `Error` instance.
* `message`: The log message.
* `...`: Message replacement parameters.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `debug` level is enabled for any stream.
#### error([object], message, ...)
Log an error message.
* `object`: An object or `Error` instance.
* `message`: The log message.
* `...`: Message replacement parameters.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `error` level is enabled for any stream.
#### fatal([object], message, ...)
Log a fatal error message.
* `object`: An object or `Error` instance.
* `message`: The log message.
* `...`: Message replacement parameters.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `fatal` level is enabled for any stream.
#### info([object], message, ...)
Log an info message.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `info` level is enabled for any stream.
#### level([level])
Get or set the log level for all streams, see [log levels](#log-levels).
* `level`: Integer level to set on all streams.
Returns the lowest level of all streams when invoked with no arguments.
#### levels([name], [level])
Get or set the log level for individual streams, see [log levels](#log-levels).
* `name`: The name of the stream or a valid index into the streams array.
* `level`: Integer level to set on a stream.
Returns an array of the levels of all streams when invoked with no arguments.
#### name
The string name of the logger.
#### names(level, [complex])
Retrieve the string name of a level from a log level integer.
* `level`: The log level integer.
* `complex`: A boolean indicating that complex bitwise log levels should be resolved to an array of names.
Returns the string log level, or if `complex` is specified an array of log level names.
If `level` could not be resolved to a string name (unknown level) it is returned.
#### trace([object], message, ...)
Log a trace message.
* `object`: An object or `Error` instance.
* `message`: The log message.
* `...`: Message replacement parameters.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `trace` level is enabled for any stream.
#### warn([object], message, ...)
Log a warn message.
* `object`: An object or `Error` instance.
* `message`: The log message.
* `...`: Message replacement parameters.
Returns a boolean indicating whether the log record was written to a stream.
When invoked with zero arguments this method returns a boolean indicating if the `warn` level is enabled for any stream.
### RingBuffer
Class used to buffer log records in an array.
#### RingBuffer([options])
Create a `RingBuffer` instance.
* `options`: Options for the ring buffer.
The `options` may contain a `limit` integer which determines the maximum number of records to buffer and a `json` boolean which indicates that the log records should be written as JSON when they are flushed.
#### flush(stream, [options])
Flush buffered log records to a stream, the buffered log records are cleared as they are written to the stream.
* `stream`: A string file system path or an existing writable stream.
* `options`: Options passed to `fs.createWriteStream` when `stream` is a string.
When `stream` is a string the created writable stream is destroyed once all records have been written, otherwise if a writable stream is passed you should destroy the stream when necessary.
If `stream` is a string and no `options` are passed the `w` mode is used with `utf8` encoding.
Returns the writable stream.
## Credits
This module is inspired by [bunyan][bunyan], by far the best logging library for [node][node]. Thanks to [trentm][trentm] for the elegant library.
The following functions have been borrowed more or less verbatim from [bunyan][bunyan]:
* `circular` (`safeCycles`)
* `getCallerInfo` (`getCaller3Info`)
* `getFullErrorStack`
* `serializers` (`stdSerializers`)
### Caveats
Bugs notwithstanding, the following list of caveats apply:
* `dtrace`: This library has no `dtrace` support as it is far less likely to be required for command line interfaces. Furthermore, we have had intermittent compile errors while building `dtrace` on Linux which at times has broken automated deployment.
* `rotating-file`: The rotating file stream type has not been implemented as it is more applicable to long running services, if it is ever implemented it will be based on file size as opposed to daily rotation.
This library does not provide a command line tool to inspect JSON log records as it is designed to be compatible with `bunyan(1)` which you can use to view and query JSON logs.
## License

@@ -355,2 +782,4 @@

[bunyan]: https://github.com/trentm/node-bunyan
[node]: http://nodejs.org/
[trentm]: https://github.com/trentm

@@ -360,5 +789,9 @@ [bin]: https://github.com/freeformsystems/cli-logger/tree/master/bin

[child]: https://github.com/freeformsystems/cli-logger/tree/master/bin/child
[color]: https://github.com/freeformsystems/cli-logger/tree/master/bin/color
[json]: https://github.com/freeformsystems/cli-logger/tree/master/bin/json
[prefix]: https://github.com/freeformsystems/cli-logger/tree/master/bin/prefix
[record]: https://github.com/freeformsystems/cli-logger/tree/master/bin/record
[ringbuffer]: https://github.com/freeformsystems/cli-logger/tree/master/bin/ringbuffer
[serialize]: https://github.com/freeformsystems/cli-logger/tree/master/bin/serialize
[source]: https://github.com/freeformsystems/cli-logger/tree/master/bin/source

@@ -60,6 +60,2 @@ var fs = require('fs');

.to.eql(ringbuffer.limit);
ringbuffer.write(ringbuffer.records[0].msg);
expect(ringbuffer.records.length)
.to.eql(logger.keys.length)
.to.eql(ringbuffer.limit);
done();

@@ -66,0 +62,0 @@ });

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc