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

debug-logger

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

debug-logger - npm Package Compare versions

Comparing version 0.2.0 to 0.3.0

178

debug-logger.js

@@ -8,2 +8,3 @@ 'use strict';

exports.getBackColor = getBackColor;
exports.debug = vmDebug;

@@ -25,42 +26,128 @@ exports.inspectOptions = {};

exports.levels = {
trace : {
color : getForeColor('cyan'),
prefix : 'TRACE ',
namespaceSuffix : ':trace',
level : 0
},
debug : {
color : getForeColor('blue'),
prefix : 'DEBUG ',
namespaceSuffix : ':debug'
namespaceSuffix : ':debug',
level : 1
},
log : {
color : '',
prefix : ' LOG ',
level : 2
},
info : {
color : getForeColor('green'),
prefix : ' INFO '
prefix : ' INFO ',
level : 3
},
warn : {
color : getForeColor('yellow'),
prefix : ' WARN '
prefix : ' WARN ',
level : 4
},
error : {
color : getForeColor('red'),
prefix : ' ERROR '
prefix : ' ERROR ',
level : 5
}
};
exports.styles = {
bold : '\x1b[1m',
underline : '\x1b[4m',
inverse : '\x1b[7m'
};
function getLogLevel(namespace) {
if(!process.env.DEBUG_LEVEL) {
return 0;
}
var debugLevel = process.env.DEBUG_LEVEL.toLowerCase();
if(debugLevel.indexOf('*:') === 0){
return hasLogLevel(debugLevel.slice(2)) || 0;
}
var hasLevel = hasLogLevel(debugLevel);
if(hasLevel !== null){
return hasLevel;
}
if(!namespace) {
return 0;
}
//currently we will only process the first part of namespace
var appNamespace = namespace.split(':')[0].toLowerCase();
var debugLevelParts = debugLevel.split(',');
var i;
for(i = 0; i < debugLevelParts.length; i++){
var parts = debugLevelParts[i].split(':');
if(appNamespace === parts[0]){
return hasLogLevel(parts[parts.length-1]) || 0;
}
}
return 0;
}
function hasLogLevel(level) {
if(!level) {
return null;
}
if (!isNaN(level)){
return level;
}
else if(isString(level) && exports.levels[level]){
return exports.levels[level].level || 0;
}
return null;
}
function isString(str){
return typeof str === 'string' || str instanceof String;
}
function hasFormattingElements(str){
if(!str) { return false; }
var res = false;
['%s', '%d', '%j'].forEach(function(elem){
if(str.indexOf(elem) >= 0) {
res = true;
}
});
return res;
}
function getErrorMessage(e) {
var errorStrings = ['', ''];
var errorStrings = [' ' + e];
if ( typeof e === 'undefined') {
if (typeof e === 'undefined') {
return errorStrings;
}
if ( typeof e === 'string' || e instanceof String) {
errorStrings[0] = ' ' + e;
if (e === null) {
return errorStrings;
}
if ( e instanceof Error) {
if (e instanceof Date) {
return errorStrings;
}
if (e instanceof Error) {
errorStrings[0] = ' ' + e.toString();
if (e.stack) {
errorStrings[1] = 'Stack trace:\n' + e.stack;
errorStrings[1] = 'Stack trace';
errorStrings[2] = e.stack;
}
return errorStrings;
}
if (e && typeof e.toString !== 'undefined') {
errorStrings[0] = ' ' + e.toString();
if (typeof e === 'object' || e instanceof Object) {
if (typeof e.toString !== 'undefined') {
errorStrings[0] = ' ' + e.toString();
}
errorStrings[1] = 'Inspected object';
errorStrings[2] = util.inspect(e, exports.inspectOptions);
}
errorStrings[1] = 'Inspected object:\n' + util.inspect(e, exports.inspectOptions);
return errorStrings;

@@ -81,27 +168,64 @@ }

var debugInstances = {};
function getDebugInstance(namespace){
if(!debugInstances[namespace]){
debugInstances[namespace] = vmDebug(namespace);
}
return debugInstances[namespace];
}
function debugLogger(namespace) {
var levels = exports.levels;
var defaultPadding = '\n' + getPadding(2);
var log = vmDebug(namespace);
var debugLoggers = { 'default': log };
var defaultPadding = '\n';
var debugLoggers = { 'default': getDebugInstance.bind(this, namespace) };
var logger = {};
logger.logLevel = getLogLevel(namespace);
Object.keys(levels).forEach(function(level) {
var loggerNamespaceSuffix = levels[level].namespaceSuffix ? levels[level].namespaceSuffix : 'default';
Object.keys(levels).forEach(function(levelName) {
var loggerNamespaceSuffix = levels[levelName].namespaceSuffix ? levels[levelName].namespaceSuffix : 'default';
if(!debugLoggers[loggerNamespaceSuffix]){
debugLoggers[loggerNamespaceSuffix] = vmDebug(namespace + loggerNamespaceSuffix);
debugLoggers[loggerNamespaceSuffix] = getDebugInstance.bind(this, namespace + loggerNamespaceSuffix);
}
var levelLog = debugLoggers[loggerNamespaceSuffix];
var color = vmDebug.useColors ? levels[level].color : '';
var levelLogger = debugLoggers[loggerNamespaceSuffix];
var color = vmDebug.useColors ? levels[levelName].color : '';
var reset = vmDebug.useColors ? exports.colorReset : '';
var inspectionHighlight = vmDebug.useColors ? exports.styles.bold : '';
logger[level] = function (message, e) {
var errorStrings = getErrorMessage(e);
var padding = errorStrings[1] !== '' ? defaultPadding : '';
levelLog(color + levels[level].prefix + reset + message + errorStrings[0] + padding + errorStrings[1]);
logger[levelName] = function () {
if (logger.logLevel > logger[levelName].level) { return; }
var levelLog = levelLogger();
if (isString(arguments[0]) && hasFormattingElements(arguments[0])){
arguments[0] = color + levels[levelName].prefix + reset + arguments[0];
return levelLog.apply(this, arguments);
}
var selfArguments = arguments;
var errorStrings = Object.keys(selfArguments).map(function(key){
return getErrorMessage(selfArguments[key]);
});
var message = "";
var inspections = "";
var i, param;
var n = 1;
for(i=0; i<errorStrings.length; i++){
param = errorStrings[i];
message += param[0];
if (param.length > 1) {
var highlightStack = param[1].indexOf('Stack') >= 0 ? color : '';
inspections += defaultPadding +
inspectionHighlight + '\\/\\/ ' + param[1] + ' #' + n++ + ' \\/\\/' + reset + '\n' +
highlightStack + param[2] + reset;
}
};
levelLog(color + levels[levelName].prefix + reset + message + inspections);
};
logger[level].logger = levelLog;
logger[level].enabled = levelLog.enabled;
logger[levelName].level = levels[levelName].level;
logger[levelName].logger = function(){ return levelLogger(); };
logger[levelName].enabled = function(){ return levelLogger().enabled; };
});

@@ -108,0 +232,0 @@

var log = require('..')('myapp');
// The below only shows up if environment variable DEBUG includes "myapp" namespace
log.trace("I'm a trace output");
log.debug("I'm a debug output");
log.log("I'm a log output");
log.info("I'm an info output");

@@ -12,3 +14,3 @@ log.warn("I'm a warn output");

var debugLogger = require('..');
if (log.debug.enabled) {
if (log.debug.enabled()) {
// This only runs if environment variable DEBUG includes "myapp:debug" namespace

@@ -29,7 +31,19 @@ log.debug("Debug is enabled, let's inspect 'debugLogger.levels':", debugLogger.levels);

console.log();
log.info.logger("the default instance of debug, using 'myapp' namespace");
log.debug.logger("the debug instance of debug, using 'myapp:debug' namespace");
log.warn("You can use log.<level>(err) and the stack trace is printed on the level's color");
log.warn(err);
console.log();
log.log("Multiple", "arguments", "including", "objects:", { obj: 'obj'}, "makes life easier");
log.warn("util.format style string: %s, number: %d and json: %j.", "foo", 13, { obj: 'json'});
console.log();
log.info.logger()("the default instance of debug, using 'myapp' namespace");
log.debug.logger()("the debug instance of debug, using 'myapp:debug' namespace");
var debug = debugLogger.debug('myapp:visionmedia');
debug('Nothing tastes better than the original!');
console.log();
debugLogger.levels.error.color = debugLogger.getForeColor('magenta');

@@ -59,12 +73,25 @@ debugLogger.levels.debug.color = debugLogger.getBackColor('cyan') + debugLogger.getForeColor('white');

prefix : 'SILLY ',
namespaceSuffix : ':silly'
namespaceSuffix : ':silly',
level : 0
};
var sillyLog = debugLogger('myapp');
sillyLog.info("Is silly logger enabled? " + sillyLog.silly.enabled);
if(sillyLog.silly.enabled){
sillyLog.info("Is silly logger enabled? " + sillyLog.silly.enabled());
if(sillyLog.silly.enabled()){
sillyLog.silly("I'm a silly output");
} else {
console.log("Silly is disabled, please add 'myapp:silly' namespace to DEBUG environment variable");
console.log("e.g.: export DEBUG=$DEBUG,myapp:silly");
console.log("e.g.: export DEBUG=$DEBUG,myapp:silly\n");
}
if (!log.log.enabled()) {
// This only runs if environment variable DEBUG includes "myapp" namespace
console.log("You probably haven't seen much because the default logger is disabled");
console.log("Please add 'myapp' namespace to DEBUG environment variable and try again");
console.log("e.g.: export DEBUG=$DEBUG,myapp");
} else {
console.log("\nNow set DEBUG_LEVEL environment variable to warn and run this example again");
console.log("e.g.: export DEBUG_LEVEL=warn");
}
console.log();

13

package.json
{
"name": "debug-logger",
"version": "0.2.0",
"description": "A wrapper for visionmedia's debug logger, adding levels and colored output",
"version": "0.3.0",
"description": "A wrapper for visionmedia/debug logger, adding levels and colored output",
"main": "debug-logger.js",

@@ -14,3 +14,8 @@ "repository": {

"levels",
"colors"
"colors",
"colours",
"log",
"info",
"warn",
"error"
],

@@ -23,4 +28,4 @@ "author": {

"dependencies": {
"debug": "~2.1.0"
"debug": "^2.1.0"
}
}

@@ -6,7 +6,7 @@ [![npm version](https://badge.fury.io/js/debug-logger.svg)](http://badge.fury.io/js/debug-logger)

A thin wrapper for visionmedia's debug logger, adding levels and colored output.
A thin wrapper for visionmedia/debug logger, adding levels and colored output.
## Overview
[visionmedia/debug](https://github.com/visionmedia/debug) is a ubitiquous logging library with 1000+ dependants. Given how widespread it is and the convenience of namespaces it is a great logger for library modules.
`debug-logger` is a convenicence wrapper around `debug` that adds level based coloured output. Each instance of `debug-logger` contains 2 instances of `debug`, one for general purpose logging and another using `namespace:debug` for debug logs.
`debug-logger` is a convenience wrapper around `debug` that adds level based coloured output. Each instance of `debug-logger` contains 2 instances of `debug`, one for general purpose logging and another using `namespace:debug` for debug logs.

@@ -103,7 +103,12 @@ AppsCot uses `debug-logger` in [waterline-orientdb](https://github.com/appscot/waterline-orientdb).

## Methods
###### `log.debug(message, [Error|Object])`
###### `log.info(message, [Error|Object])`
###### `log.warn(message, [Error|Object])`
###### `log.error(message, [Error|Object])`
Prints the message prepended by log level. If the terminal supports colors, the level will be one of: blue, green, yellow, red. If an Error is provided, the toString() and call stack will be outputted. If an Object is provided the toString() and util.inspect() will be outputted. Example:
### Instance Methods
#### `log.trace([data][, ...])`
#### `log.debug([data][, ...])`
#### `log.log([data][, ...])`
#### `log.info([data][, ...])`
#### `log.warn([data][, ...])`
#### `log.error([data][, ...])`
Prints the data prepended by log level. If the terminal supports colors, the level will be one of: blue, green, yellow, red. If an Error is provided, the toString() and call stack will be outputted. If an Object is provided the toString() and util.inspect() will be outputted. Example:
```

@@ -113,4 +118,13 @@ myapp:debug DEBUG I'm a debug output +0ms

```
This function can take multiple arguments in a printf()-like way, if formatting elements are not found in the first string then util.inspect is used on each argument.
###### `getForeColor(color)`
#### `log[level].logger()`
Returns the default debug instance used by `level`.
#### `log[level].enabled()`
Boolean indicating if `level`'s logger is enabled.
### Module Methods
#### `getForeColor(color)`
Returns an ANSI foreground color code string. `color` is one of `black, red, green, yellow, blue, magenta, cyan, white`

@@ -123,10 +137,7 @@ Example:

###### `getBackColor(color)`
#### `getBackColor(color)`
Returns an ANSI background color code string.
## Properties
###### `log[level].logger`
Returns the default debug instance used by `level`.
###### `log[level].enabled`
Boolean indicating if `level`'s logger is enabled.
#### `debug`
Returns visionmedia/debug module.
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