utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var noop = exports.noop = function(){};
  2. exports.extend = function extend(dest, source) {
  3. for (var prop in source) {
  4. dest[prop] = source[prop];
  5. }
  6. };
  7. exports.eventEmitterListenerCount =
  8. require('events').EventEmitter.listenerCount ||
  9. function(emitter, type) { return emitter.listeners(type).length; };
  10. exports.bufferAllocUnsafe = Buffer.allocUnsafe ?
  11. Buffer.allocUnsafe :
  12. function oldBufferAllocUnsafe(size) { return new Buffer(size); };
  13. exports.bufferFromString = Buffer.from ?
  14. Buffer.from :
  15. function oldBufferFromString(string, encoding) {
  16. return new Buffer(string, encoding);
  17. };
  18. exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) {
  19. var logFunction = require('debug')(identifier);
  20. if (logFunction.enabled) {
  21. var logger = new BufferingLogger(identifier, uniqueID, logFunction);
  22. var debug = logger.log.bind(logger);
  23. debug.printOutput = logger.printOutput.bind(logger);
  24. debug.enabled = logFunction.enabled;
  25. return debug;
  26. }
  27. logFunction.printOutput = noop;
  28. return logFunction;
  29. };
  30. function BufferingLogger(identifier, uniqueID, logFunction) {
  31. this.logFunction = logFunction;
  32. this.identifier = identifier;
  33. this.uniqueID = uniqueID;
  34. this.buffer = [];
  35. }
  36. BufferingLogger.prototype.log = function() {
  37. this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]);
  38. return this;
  39. };
  40. BufferingLogger.prototype.clear = function() {
  41. this.buffer = [];
  42. return this;
  43. };
  44. BufferingLogger.prototype.printOutput = function(logFunction) {
  45. if (!logFunction) { logFunction = this.logFunction; }
  46. var uniqueID = this.uniqueID;
  47. this.buffer.forEach(function(entry) {
  48. var date = entry[0].toLocaleString();
  49. var args = entry[1].slice();
  50. var formatString = args[0];
  51. if (formatString !== (void 0) && formatString !== null) {
  52. formatString = '%s - %s - ' + formatString.toString();
  53. args.splice(0, 1, formatString, date, uniqueID);
  54. logFunction.apply(global, args);
  55. }
  56. });
  57. };