New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

fm-log

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fm-log - npm Package Compare versions

Comparing version 0.8.2 to 1.0.0-beta0

.editorconfig

270

lib/log.js
"use strict";
var chalk = require( "chalk" );
var http = require( "http" );
var util = require( "util" );
var http = require( "http" );
var util = require( "util" );

@@ -32,2 +32,8 @@ /**

/**
* The stream to write log messages to.
* @type {process.stdout|Stream}
*/
var globalStream = process.stdout;
/**
* An object that will not have its source traced when it's logged.

@@ -40,3 +46,3 @@ * @param {String} message The message to log

}
Untraceable.prototype.toString = function() {
Untraceable.prototype.toString = function Untraceable$toString() {
return this.message;

@@ -47,6 +53,8 @@ };

* Determines if a given message should be logged. The purpose is to avoid logging the same message continously.
* @param {String} level
* @param {Logger} logger
* @param {String} message The message being logged.
* @returns {boolean} true if the message should be logged; false otherwise.
*/
var shouldLog = function( level, logger, message ) {
function shouldLog( level, logger, message ) {
if( lastMessage && message == lastMessage.message && level == lastMessage.level && logger == lastMessage.logger ) {

@@ -57,3 +65,3 @@ ++lastMessageRepeated;

} else if( lastMessage && 0 < lastMessageRepeated ) {
lastMessage = undefined;
lastMessage = undefined;
lastLogger( new Untraceable( "Last message repeated " + lastMessageRepeated + " times." ) );

@@ -63,6 +71,10 @@ lastMessageRepeated = 0;

} else {
lastMessage = { level : level, logger : logger, message : message };
lastMessage = {
level : level,
logger : logger,
message : message
};
}
return true;
};
}

@@ -79,6 +91,8 @@ /**

* messages line up.
* @param {Stream} [stream] The stream to log to.
* @constructor
*/
function Logger( prefix ) {
function Logger( prefix, stream ) {
this.prefix = prefix;
this.stream = stream || globalStream;
}

@@ -89,13 +103,17 @@

* @param {String} prefix The prefix to pad.
* @param {Boolean} multiline Are we constructing the prefix for the second or later line in a multiline construct?
* @param {Boolean} [multiline] Are we constructing the prefix for the second or later line in a multiline construct?
* @returns {string} The padded prefix.
*/
var constructPrefix = function( prefix, multiline ) {
function constructPrefix( prefix, multiline ) {
// If there is no prefix and nothing else has a prefix, then the .module construction scheme is never used.
// In this case, don't pad anything.
if( !prefix && !moduleMaxLength ) return "";
if( !prefix && !moduleMaxLength ) {
return "";
}
// If we have a prefix, pad it to the max prefix length, otherwise, leave off the parenthesis and just use spaces.
return (prefix && !multiline) ? "(" + pad( prefix, moduleMaxLength, " " ) + ")" : pad( "", moduleMaxLength + 2, " " );
};
return ( prefix && !multiline ) ? "(" + pad( prefix, moduleMaxLength, " " ) + ")" : pad( "",
moduleMaxLength + 2,
" " );
}

@@ -106,10 +124,10 @@ /**

* @param {String} message The message that should be prefixed.
* @param {Boolean} multiline Are we constructing the prefix for the second or later line in a multiline construct?
* @param {Boolean} [multiline] Are we constructing the prefix for the second or later line in a multiline construct?
* @returns {string} The properly prefixed message.
*/
var prefixMessage = function( prefix, message, multiline ) {
function prefixMessage( prefix, message, multiline ) {
// Pad the prefix so that all logged messages line up
prefix = constructPrefix( prefix, multiline );
return (prefix) ? (prefix + " " + message ) : message;
};
return prefix ? ( prefix + " " + message ) : message;
}

@@ -123,8 +141,8 @@ /**

*/
var pad = function( padWhat, length, padWith ) {
length = length || 2;
padWith = padWith || "0";
var padding = length - ("" + padWhat).length;
return padding ? (new Array( padding + 1 ).join( padWith ) + padWhat) : padWhat;
};
function pad( padWhat, length, padWith ) {
length = length || 2;
padWith = padWith || "0";
var padding = length - ( "" + padWhat ).length;
return padding ? ( new Array( padding + 1 ).join( padWith ) + padWhat ) : padWhat;
}

@@ -136,3 +154,3 @@ /**

*/
var unrollRequest = function( message ) {
function unrollRequest( message ) {
if( message instanceof http.IncomingMessage && message.originalUrl ) {

@@ -163,3 +181,3 @@ message = {

originalUrl : message.originalUrl
}
};
}

@@ -173,8 +191,12 @@ return message;

*/
Logger.prototype.debug = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.debug = function Logger$debug( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[DEBUG ]", this, chalk.grey, this.debug.bind( this ), message );
};
/**

@@ -184,8 +206,12 @@ * Log an informational message.

*/
Logger.prototype.info = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.info = function Logger$info( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[INFO ]", this, chalk.cyan, this.info.bind( this ), message );
};
/**

@@ -195,8 +221,12 @@ * Log a notice.

*/
Logger.prototype.notice = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.notice = function Logger$notice( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[NOTICE]", this, chalk.green, this.notice.bind( this ), message );
};
/**

@@ -206,8 +236,12 @@ * Log a warning.

*/
Logger.prototype.warn = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.warn = function Logger$warn( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[WARN ]", this, chalk.yellow, this.warn.bind( this ), message );
};
/**

@@ -217,8 +251,12 @@ * Log an error.

*/
Logger.prototype.error = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.error = function Logger$error( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[ERROR ]", this, chalk.red, this.error.bind( this ), message );
};
/**

@@ -228,7 +266,10 @@ * Log a critical event.

*/
Logger.prototype.critical = function( message ) {
if( !module.exports.enableLogging ) return;
message = (typeof message == "string" || message instanceof String) ? formatString.apply( this, arguments ) : message;
Logger.prototype.critical = function Logger$critical( message ) {
if( !module.exports.enableLogging ) {
return;
}
message = ( typeof message == "string" || message instanceof String ) ? formatString.apply( this,
arguments ) : message;
message = unrollRequest( message );
preLog( "[CRITIC]", this, function( str ) {
preLog( "[CRITIC]", this, function colorize( str ) {
return chalk.bold( chalk.red( str ) );

@@ -240,4 +281,4 @@ }, this.critical.bind( this ), message );

Logger.prototype.verbose = Logger.prototype.debug;
Logger.prototype.err = Logger.prototype.error;
Logger.prototype.crit = Logger.prototype.critical;
Logger.prototype.err = Logger.prototype.error;
Logger.prototype.crit = Logger.prototype.critical;

@@ -248,5 +289,6 @@ /**

*/
var formatString = function() {
return (1 < arguments.length) ? util.format.apply( this, arguments ) : arguments[ 0 ];
function formatString() {
return ( 1 < arguments.length ) ? util.format.apply( this, arguments ) : arguments[ 0 ];
}
/**

@@ -258,5 +300,5 @@ * Pre-processes a logging subject. Like breaking it into further subjects or grabbing stacks from Errors.

* @param {Function} more A callback to use when further output needs to be logged.
* @param {String} message The subject that should be logged.
* @param {String|Error} message The subject that should be logged.
*/
var preLog = function( level, logger, colorizer, more, message ) {
function preLog( level, logger, colorizer, more, message ) {
if( !shouldLog( level, logger, message ) ) {

@@ -291,3 +333,3 @@ return;

if( message === void(0) ) {
if( message === void 0 ) {
message = "undefined";

@@ -301,7 +343,7 @@ }

var toLog = generateLogStack( level, logger, message, colorizer );
log( toLog );
log( toLog, logger.stream, logger.sync );
if( location ) {
more( location );
}
};
}

@@ -315,3 +357,3 @@ /**

*/
var analyzeStack = function( stack, stackIndex ) {
function analyzeStack( stack, stackIndex ) {
stackIndex = stackIndex || 2;

@@ -325,22 +367,25 @@

*/
var callSitePattern = new RegExp( /at (?:(.*) )?\(?(.*):(\d+):(\d+)\)?/g );
var sites = stack.match( callSitePattern );
var callSitePattern = /at (?:(.*) )?\(?(.*):(\d+):(\d+)\)?/g;
var sites = stack.match( callSitePattern );
// The method that invoked the logger is located at index 2 of the stack
if( sites && stackIndex <= sites.length ) {
var callSiteElementPattern = new RegExp( /at (?:(.*) )?\(?(.*):(\d+):(\d+)\)?/ );
var callSiteElementPattern = /at (?:(.*) )?\(?(.*):(\d+):(\d+)\)?/;
// Pick apart
var callSiteElements = sites[ stackIndex ].match( callSiteElementPattern );
var functionName, fileName, line, column;
var functionName = "";
var fileName = "";
var line = -1;
var column = -1;
// Assume either 4 (no function name) or 5 elements.
if( callSiteElements.length == 5 ) {
functionName = callSiteElements[ 1 ];
fileName = callSiteElements[ 2 ];
line = callSiteElements[ 3 ];
column = callSiteElements[ 4 ];
fileName = callSiteElements[ 2 ];
line = callSiteElements[ 3 ];
column = callSiteElements[ 4 ];
} else {
functionName = "(unnamed)";
fileName = callSiteElements[ 1 ];
line = callSiteElements[ 2 ];
column = callSiteElements[ 3 ];
fileName = callSiteElements[ 1 ];
line = callSiteElements[ 2 ];
column = callSiteElements[ 3 ];
}

@@ -351,3 +396,3 @@

return null;
};
}

@@ -359,5 +404,5 @@ /**

*/
var stringify = function( subject ) {
function stringify( subject ) {
var cache = [];
var json = JSON.stringify( subject, function( key, value ) {
var json = JSON.stringify( subject, function serializeKv( key, value ) {
if( typeof value === "object" && value !== null ) {

@@ -384,5 +429,5 @@ if( cache.indexOf( value ) !== -1 ) {

*/
var generateLogStack = function( level, logger, subject, colorizer ) {
var subjectString = (util.isArray( subject ) || typeof( subject ) == "object") ? stringify( subject ) : subject.toString();
var lines = subjectString.split( "\n" );
function generateLogStack( level, logger, subject, colorizer ) {
var subjectString = ( util.isArray( subject ) || typeof subject == "object" ) ? stringify( subject ) : subject.toString();
var lines = subjectString.split( "\n" );

@@ -395,3 +440,5 @@ // Most common case, a single line.

for( var lineIndex = 0, lineCount = lines.length; lineIndex < lineCount; ++lineIndex ) {
lines[ lineIndex ] = colorizer( level + " " + prefixMessage( logger.prefix, lines[ lineIndex ], lineIndex > 0 ) );
lines[ lineIndex ] = colorizer( level + " " + prefixMessage( logger.prefix,
lines[ lineIndex ],
lineIndex > 0 ) );
// Replace the level prefix with whitespace for lines other than the first

@@ -403,3 +450,3 @@ if( 0 == lineIndex ) {

return 1 < lines.length ? lines : lines[ 0 ];
};
}

@@ -409,14 +456,21 @@ /**

* @param {String} message The message to log.
* @param {Stream} stream Where to log to.
* @param {Boolean} sync Should be log synchronously?
*/
var log = function( message ) {
var time = new Date();
function log( message, stream, sync ) {
var time = new Date();
var timestamp = formatDate( time );
var logger = sync ? stream.write : function delayedLog( data ) {
process.nextTick( function write() {
stream.write( data );
} );
};
if( util.isArray( message ) ) {
for( var messageIndex = 0, messageCount = message.length; messageIndex < messageCount; ++messageIndex ) {
console.log( timestamp + " " + message[ messageIndex ] );
logger.call( stream, timestamp + " " + message[ messageIndex ] + "\n" );
}
} else {
console.log( timestamp + " " + message );
logger.call( stream, timestamp + " " + message + "\n" );
}
};
}

@@ -428,6 +482,7 @@ /**

*/
var formatDate = function( date ) {
function formatDate( date ) {
return date.getFullYear() + "-" + pad( date.getMonth() + 1 ) + "-" + pad( date.getDate() ) + " " +
pad( date.getHours() ) + ":" + pad( date.getMinutes() ) + ":" + pad( date.getSeconds() ) + "." + pad( date.getMilliseconds(), 3 );
};
pad( date.getHours() ) + ":" + pad( date.getMinutes() ) + ":" + pad( date.getSeconds() ) + "." + pad( date.getMilliseconds(),
3 );
}

@@ -438,4 +493,4 @@ /**

*/
Logger.prototype.withSource = function( enable ) {
this.traceLoggingCalls = !!!enable;
Logger.prototype.withSource = function Logger$withSource( enable ) {
this.traceLoggingCalls = !enable;
return this;

@@ -445,3 +500,3 @@ };

/**
* Create and wrap a morgan instance.+
* Create and wrap a morgan instance.
* @param {String} format The format string to pass to morgan.

@@ -452,8 +507,8 @@ * @param {Object} [options] The options object that will be passed to the morgan constructor.

*/
Logger.prototype.morgan = function( format, options, how ) {
how = how || this.debug.bind( this );
options = options || {};
var Stream = require( "stream" ).Writable;
var logStream = new Stream();
logStream.write = function( data ) {
Logger.prototype.morgan = function Logger$morgan( format, options, how ) {
how = how || this.debug.bind( this );
options = options || {};
var Stream = require( "stream" ).Writable;
var logStream = new Stream();
logStream.write = function writeHandler( data ) {
// Remove trailing newline

@@ -463,12 +518,32 @@ data = data.slice( 0, data.length - 1 );

};
options.stream = logStream;
var morgan = require( "morgan" )( format, options );
options.stream = logStream;
var morgan = require( "morgan" )( format, options );
// morgan, morgan, morgan, morgan
morgan.morgan = morgan;
return function( req, res, next ) {
return function middleware( req, res, next ) {
morgan( req, res, next );
}
};
};
/**
* Send log output to the given stream.
* @param {Stream} stream
* @returns {Logger} Returns itself
*/
Logger.prototype.to = function Logger$to( stream ) {
this.stream = stream;
return this;
};
/**
* Request synchronous logging.
* @param {Boolean} [sync=true] Should the logger log synchronously?
* @returns {Logger} Returns itself
*/
Logger.prototype.sync = function Logger$sync( sync ) {
this.sync = ( typeof sync === "undefined" ) ? true : sync;
return this;
};
/**
* Construct a new Logger instance for a module with the given name.

@@ -478,5 +553,5 @@ * @param {String} [moduleName] The name of the module.

*/
Logger.fromModule = function( moduleName ) {
Logger.fromModule = function Logger$fromModule( moduleName ) {
if( !moduleName ) {
var error = new Error().stack;
var error = new Error().stack;
var matches = error.match( /at Object.<anonymous> .*[\\/](.*?):/ );

@@ -492,7 +567,8 @@ if( matches && matches.length >= 2 ) {

};
return Logger;
}());
module.exports = new Logger();
module.exports.module = Logger.fromModule;
module.exports = new Logger();
module.exports.module = Logger.fromModule;
module.exports.enableLogging = true;
{
"name": "fm-log",
"version": "0.8.2",
"version": "1.0.0-beta0",
"description": "Console logging facility for Node",
"main": "lib/log.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "mocha"
},

@@ -27,8 +27,10 @@ "repository": {

"grunt-contrib-jshint": "0.11.0",
"grunt-contrib-watch": "~0.6.1",
"should": "5.0.1"
"grunt-contrib-watch": "0.6.1",
"jscs": "2.1.0",
"mocha": "2.2.5",
"should": "7.0.4"
},
"dependencies": {
"chalk": "~1.0.0"
"chalk": "^1.1.1"
}
}

@@ -10,3 +10,3 @@ fm-log

- uses colors
- sends everything straight to `console.log`, no events, no `nextTick()`
- sends everything straight to `process.stdout` (no events, no `nextTick()`) if desired
- condenses repeated messages

@@ -57,7 +57,7 @@ - displays stack traces for logged Error instances and other multi-line content nicely

npm install fm-log
npm install fm-log
Put this in every file where you want to log:
var log = require( "fm-log" ).module();
var log = require( "fm-log" ).module();

@@ -69,2 +69,11 @@ Then just use `log.info` or one of the other logging levels shown above.

var generic = require( "fm-log" );
generic.notice( "We don't need no prefix" );
generic.notice( "We don't need no prefix" );
To log to a different stream (`process.stdout` is the default), use `.to()`:
var logger = require( "fm-log" ).to( process.stderr );
To send data straight to the output stream (without `nextTick()`), use `.sync()`:
var logger = require( "fm-log" ).sync();

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

var chalk = require( "chalk" );
var chalk = require( "chalk" );
var should = require( "should" );

@@ -6,20 +6,17 @@

var log;
var consoleLogOrig = console.log;
var consoleLog = console.log;
var result;
var Stream = require( "stream" ).Writable;
var logStream = new Stream();
logStream.write = function writeHandler( data ) {
result.push( chalk.stripColor( arguments[ 0 ] ) );
};
beforeEach( function() {
result = [];
consoleLog = function() {
result.push( chalk.stripColor( arguments[ 0 ] ) );
consoleLogOrig.apply( console, arguments );
};
console.log = consoleLog;
} );
afterEach( function() {
consoleLog = consoleLogOrig;
} );
describe( "without prefix", function() {
beforeEach( function() {
log = require( "../lib/log.js" );
log = require( "../lib/log.js" ).to( logStream );
} );

@@ -60,3 +57,3 @@

beforeEach( function() {
log = require( "../lib/log.js" ).module( "foo" );
log = require( "../lib/log.js" ).module( "foo" ).to( logStream );
} );

@@ -66,2 +63,3 @@

log.info( "!" );
result.should.have.length( 1 );
result[ 0 ].should.match( /\d \[INFO ] \(foo\) !/ );

@@ -73,3 +71,3 @@ setTimeout( done, 200 );

log.info( "!\n!" );
result.length.should.equal( 2 );
result.should.have.length( 2 );
result[ 0 ].should.match( /\d \[INFO ] \(foo\) !/ );

@@ -99,4 +97,4 @@ result[ 1 ].should.match( /\d !/ );

it( "should log multiline", function( done ) {
log = require( "../lib/log.js" ).module( "module" );
log = require( "../lib/log.js" ).module( "foo" );
log = require( "../lib/log.js" ).module( "module" ).to( logStream );
log = require( "../lib/log.js" ).module( "foo" ).to( logStream );
log.info( "!\n!" );

@@ -121,5 +119,5 @@ result.length.should.equal( 2 );

setTimeout( done, 200 );
} )
} )
} );
} );
} );

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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