Comparing version 0.1.4 to 0.2.0
@@ -10,6 +10,25 @@ /** | ||
module.exports = function(logRecord) { | ||
var consoleWatcher = module.exports = {}; | ||
/** | ||
* The watcher that will output to stdOut. | ||
* | ||
* @param {Object} logRecord The logRecord Object. | ||
*/ | ||
consoleWatcher.watcher = function(logRecord) { | ||
process.stdout.write(consoleWatcher.formatRecord(logRecord), 'utf8'); | ||
}; | ||
/** | ||
* Format a logRecord for use on console printing. | ||
* | ||
* @param {Object} logRecord The logRecord Object. | ||
* @param {boolean=} optStripColors do not use colors and formating. | ||
* @return {string} The log message formated. | ||
*/ | ||
consoleWatcher.formatRecord = function(logRecord, optStripColors) { | ||
var color; | ||
if (logRecord.level >= LogLevel.SEVERE) { | ||
color = Colors.RED | ||
color = Colors.RED; | ||
} else if (logRecord.level >= LogLevel.WARN) { | ||
@@ -23,12 +42,18 @@ color = Colors.YELLOW; | ||
var msg = color + logRecord.message + Colors.RESET; | ||
var colReset = optStripColors ? '' : Colors.RESET; | ||
var colGrey = optStripColors ? '' : Colors.GREY; | ||
color = optStripColors ? '' : color; | ||
var msg = color + logRecord.message + colReset; | ||
var now = getDateString(logRecord.date); | ||
process.stdout.write(Colors.GREY + now + (logRecord.name ? ' [' + | ||
Colors.RESET + logRecord.name + Colors.GREY + ']' : '') + ' : ' + | ||
Colors.RESET + msg, 'utf8'); | ||
process.stdout.write('\n', 'utf8'); | ||
var out = colGrey + now + (logRecord.name ? ' [' + | ||
colReset + logRecord.name + colGrey + ']' : '') + ' : ' + | ||
colReset + msg; | ||
out += '\n'; | ||
return out; | ||
}; | ||
/** | ||
@@ -35,0 +60,0 @@ * Returns a date string in the form yy/mm/dd hh:mm:ss.mmm. |
@@ -9,3 +9,10 @@ /** | ||
var Logger = require('./logger'); | ||
var consolewatcher = require('./consolewatcher'); | ||
/** @type {boolean} If this package is the root one */ | ||
var isRoot = false; | ||
/** @type {boolean} If console watcher has been registered */ | ||
var isConsoleRegistered = false; | ||
/** | ||
@@ -18,4 +25,5 @@ * Map of loggers. Use a global so that it is shared if multiple copies of the | ||
if (typeof LOGGERS == 'undefined') { | ||
var isRoot = true; | ||
LOGGERS = {'': new Logger('')}; | ||
isRoot = true; | ||
LOGGERS = {'': Logger.getSingleton()}; | ||
LOGGERS_AR = [Logger.getSingleton()]; | ||
} | ||
@@ -31,2 +39,3 @@ | ||
/** | ||
@@ -42,2 +51,3 @@ * Returns the logger for the provided namespace, creating new instances as | ||
LOGGERS[ns].setParent(getLogger(getParentNs(ns))); | ||
LOGGERS_AR.push(LOGGERS[ns]); | ||
} | ||
@@ -90,7 +100,58 @@ return LOGGERS[ns]; | ||
/** | ||
* Removes the console watcher, no more logging to the console. | ||
*/ | ||
function removeConsole() { | ||
if (!isRoot) { | ||
throw new Error('This instance is not the main one. Another package uses a' + | ||
' different version of "node-logg" and holds the actual reference to' + | ||
' the console watcher'); | ||
} | ||
if (!isConsoleRegistered) { | ||
return; | ||
} | ||
rootLogger.removeListener('', consolewatcher.watcher); | ||
isConsoleRegistered = false; | ||
} | ||
/** | ||
* Register a default watcher that just logs to the console. | ||
*/ | ||
function addConsole() { | ||
if (!isRoot) { | ||
throw new Error('This instance is not the main one. Another package uses a' + | ||
' different version of "node-logg" and holds the actual reference to' + | ||
' the console watcher'); | ||
} | ||
if (isConsoleRegistered) { | ||
return; | ||
} | ||
registerWatcher(consolewatcher.watcher); | ||
isConsoleRegistered = true; | ||
} | ||
/** | ||
* Removes all the listeners of all the logger instances including | ||
* the rootLogger. | ||
* | ||
*/ | ||
function removeAllListeners() { | ||
LOGGERS_AR.forEach(function(logger){ | ||
logger.removeAllListeners(); | ||
}); | ||
// restore console if it was registered | ||
if (isConsoleRegistered) { | ||
isConsoleRegistered = false; | ||
addConsole(); | ||
} | ||
} | ||
if (isRoot) { | ||
// Register a default watcher that just logs to the console. | ||
registerWatcher(require('./consolewatcher')); | ||
addConsole(); | ||
} | ||
module.exports = { | ||
@@ -101,4 +162,10 @@ Level: require('./level'), | ||
getTransientLogger: getTransientLogger, | ||
registerWatcher: registerWatcher | ||
} | ||
registerWatcher: registerWatcher, | ||
formatRecord: consolewatcher.formatRecord, | ||
addConsole: addConsole, | ||
removeConsole: removeConsole, | ||
removeListener: rootLogger.removeListener.bind(rootLogger), | ||
removeAllListeners: removeAllListeners, | ||
on: rootLogger.on.bind(rootLogger) | ||
}; | ||
@@ -9,12 +9,16 @@ /** | ||
var util = require('util'); | ||
var LogRecord = require('./logrecord'); | ||
var LogLevel = require('./level'); | ||
var EventEmitter = require('events').EventEmitter; | ||
/** | ||
* @param {string} name The name for this logger, will get shown in the logs. | ||
* @extends {events.EventEmitter} | ||
* @constructor | ||
*/ | ||
function Logger(name) { | ||
EventEmitter.call(this); | ||
this.name = name; | ||
@@ -25,2 +29,4 @@ this.parent_ = null; | ||
this.finest = this.log.bind(this, LogLevel.FINEST); | ||
this.finer = this.log.bind(this, LogLevel.FINER); | ||
this.fine = this.log.bind(this, LogLevel.FINE); | ||
@@ -31,5 +37,22 @@ this.info = this.log.bind(this, LogLevel.INFO); | ||
} | ||
util.inherits(Logger, EventEmitter); | ||
/** @type {?Logger} The Logger singleton instance */ | ||
Logger._instance = null; | ||
/** | ||
* Static function that returns a singleton instance of the | ||
* Logger class, effectively being the "rootLogger". | ||
* | ||
* @return {Logger} The rootLoger. | ||
*/ | ||
Logger.getSingleton = function() { | ||
if (Logger._instance) { | ||
return Logger._instance; | ||
} | ||
return (Logger._instance = new Logger('')); | ||
}; | ||
/** | ||
* Sets the explicit log level for this logger. | ||
@@ -75,16 +98,6 @@ * @param {LogLevel} level | ||
Logger.prototype.registerWatcher = function(watcher) { | ||
this.watchers_.push(watcher); | ||
this.on('', watcher); | ||
}; | ||
/** | ||
* Gets the array of watchers registered on this logger. | ||
* @return {Array.<function(LogRecord)>} | ||
*/ | ||
Logger.prototype.getWatchers = function() { | ||
return this.watchers_; | ||
}; | ||
/** | ||
* Logs at a specific level. | ||
@@ -95,12 +108,30 @@ * @param {LogLevel} level | ||
Logger.prototype.log = function(level, var_args) { | ||
var logRecord = new LogRecord(level, this.name, arguments); | ||
var rootLogger = Logger.getSingleton(); | ||
// | ||
// Event emitting plan in sequence: | ||
// | ||
// * If message is loggable emit on global key from rootLogger. | ||
// * If not rootLogger emit LEVEL event on instance and bubble up to and | ||
// including rootLogger. | ||
// * If not rootLogger emit Logger NAME event on instance and bubble up to and | ||
// including rootLogger. | ||
// | ||
// | ||
if (this.isLoggable(level)) { | ||
var logRecord = new LogRecord(level, this.name, arguments); | ||
rootLogger.emit('', logRecord); | ||
} | ||
if (this.name) { | ||
var name; | ||
var logger = this; | ||
while (logger) { | ||
logger.getWatchers().forEach(function(watcher) { | ||
watcher(logRecord); | ||
}); | ||
rootLogger.emit(level, logRecord); | ||
while (rootLogger !== logger) { | ||
name = logger.name | ||
rootLogger.emit(name, logRecord); | ||
logger = logger.getParent(); | ||
} | ||
} | ||
}; | ||
@@ -107,0 +138,0 @@ |
{ | ||
"name" : "logg", | ||
"version" : "0.1.4", | ||
"version" : "0.2.0", | ||
"description" : "Logging library that allows for hierarchical loggers, multiple log levels, and flexible watching of log records.", | ||
@@ -5,0 +5,0 @@ "keywords" : ["log", "logging", "logger", "hierarchical", "handler", "watcher"], |
175
README.md
@@ -20,7 +20,7 @@ # Node-Logging | ||
var logging = require('logg'); | ||
var logger = logging.getLogger('my.class); | ||
var logger = logging.getLogger('my.class'); | ||
logger.setLogLevel(logging.Level.WARN); | ||
logger.info('This will not show up'); | ||
logger.warn('But warnings will', new Error('aargg')); | ||
logger.warn('But warnings will', new Error('aargg')); | ||
@@ -33,3 +33,3 @@ Loggers are arranged in a hierarchy based on their names, separated by dots. Log reporting levels are inherited based on the hierarchy, INFO being the default level. For example, the following will silence everything but errors within the `subproject` namespace: | ||
var d = logging.getLogger('project.subproject.bam'); | ||
logging.getLogger('project.subproject').setLogLevel(logging.Level.SEVERE); | ||
@@ -45,1 +45,168 @@ | ||
A default watcher is automatically registered which outputs to the console. | ||
## API | ||
### logg.getLogger(name) | ||
* *name* **string** The logger's name using dot nottation. | ||
Will create a new Logger instance and return it. | ||
### logg.registerWatcher(callback) | ||
* *callback* **Function(LogRecord)** The callback of the watcher. | ||
Attach a listener on the root logger capturing all log messages. This is legacy and sugar for `logg.on('', callback)`. | ||
Read about the callback's argument `LogRecord` in [logg.LogRecord](#logglogrecord). | ||
### logg.on(eventType, callback) | ||
* *eventType* **string** The event type. | ||
* *callback* **Function(LogRecord)** The callback of the event. | ||
Attach a listener for a specific logger. Read about the events emitted by logg in the [Events Emitted](#events-emitted) section. | ||
Read about the callback's argument `LogRecord` in [logg.LogRecord](#logglogrecord). | ||
### logg.removeListener(eventType, callback) | ||
* *eventType* **string** The event type. | ||
* *callback* **Function(LogRecord)** The callback of the event. | ||
Remove a listener that was attached using the `on` method. | ||
### logg.removeAllListeners() | ||
Removes any listeners attached, including ones using the `registerWatcher` method. | ||
### logg.removeConsole() | ||
Stop logging to console. By default node-logg will log to the console. | ||
### logg.addConsole() | ||
Will start logging to the console. | ||
### logg.formatRecord(logRecord, optStripColors) | ||
* *logRecord* **logg.LogRecord** The log record Object. | ||
* *optStripColors* **boolean** Optionally strip colors, default is `false`. | ||
* *Returns* **string** Always string. | ||
Create a pretty formated message from the log record provided. By default `formatRecord` will return a string containing special codes that color the content. If you want to get the plain text version set the `optStripColors` option to `true`. | ||
### logg.LogRecord | ||
The logg.LogRecord class is a single log item. It is provided to every log message listener. The properties of a `LogRecord` are: | ||
* **level** *number* The Level of the message (e.g. `100`). | ||
* **name** *string* The name of the logger emitting the message (e.g. `app.model.apples`). | ||
* **rawArgs** *Array* An array containing all the arguments passed to the logger. | ||
* **date** *Date* A Date Object. | ||
* **message** *string* A concatenation of `rawArgs` with Objects and Arrays expanded. | ||
### logg.Level | ||
The default logging levels available by node-logg. `logg.Level` is an enumeration of numbers: | ||
```js | ||
logg.Level.SEVERE; // 1000 | ||
logg.Level.WARN; // 800 | ||
logg.Level.INFO; // 600 | ||
logg.Level.FINE; // 400 | ||
logg.Level.FINER; // 200 | ||
logg.Level.FINEST; // 100 | ||
``` | ||
## Events Emitted | ||
node-logg emits three type of events. All events emitted contain one item, the [logg.LogRecord](#logglogrecord). The event types are: | ||
### The rootLogger | ||
Captures all messages on the root level that are loggable. The special *rootLogger* emits events using the `''` key (empty string). | ||
```js | ||
logg.on('', function(logRecord) { /* ... */}); | ||
``` | ||
You can configure the logging level by using the `setLogLevel` method of the root logger: | ||
```js | ||
logg.rootLogger.setLogLevel(logg.Level.INFO); | ||
``` | ||
### The Loggers Events | ||
Every logger will emit it's own event which will bubble up to the rootLogger. So if a logger is named `app.model.apple` three events will be emitted using these types: | ||
1. `app.model.apple` first emitted event. | ||
2. `app.model` second emitted event. | ||
3. `app` third emitted event. | ||
These type of events will be emitted irrespective of the logging level set. | ||
### The Levels Events | ||
All messages emit events with their [Level](#logglevel) as the event type. This in effect makes the event-type a number. | ||
These type of events will be emitted irrespective of the logging level set. | ||
## Examples | ||
Set up the node-logg to save messages to syslog for use in production. In this example the [node-syslog](https://github.com/schamane/node-syslog#readme) package is used. | ||
```js | ||
var logg = require('logg'); | ||
var syslog = require('node-syslog'); | ||
// setup syslog | ||
syslog.init('kickq', syslog.LOG_PID | syslog.LOG_ODELAY, syslog.LOG_LOCAL0); | ||
// do not log to console. | ||
logg.removeConsole(); | ||
// listen for log messages | ||
logg.on('', function(logRecord) { | ||
// format the message | ||
var message = logg.formatRecord(logRecord, true); | ||
// relay to syslog using LOG_INFO for WARN and above messages | ||
// LOG_DEBUG for the test | ||
if (logg.Level.WARN <= logRecord.level) { | ||
syslog.log(syslog.LOG_INFO, message); | ||
} else { | ||
syslog.log(syslog.LOG_DEBUG, message); | ||
} | ||
}); | ||
``` | ||
During development you may want to see all the messages of a specific logger: | ||
```js | ||
// this is a debug file... | ||
var logg = require('logg'); | ||
// display messages to console | ||
logg.addConsole(); | ||
// set logging level of "app.model.apple" to lowest. | ||
logg.getLogger('app.model.apple').setLogLevel(logg.Level.FINEST); | ||
``` | ||
## Licence | ||
The MIT License (MIT) | ||
Copyright (c) 2011 Daniel Pupius | ||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
24694
543
210