logger.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* logger.coffee */
  2. (function() {
  3. var chalk, cli, logger, transports, util, winston,
  4. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  5. hasProp = {}.hasOwnProperty;
  6. chalk = require('chalk');
  7. winston = require('winston');
  8. util = require('util');
  9. cli = (function(superClass) {
  10. extend(cli, superClass);
  11. /* Winston transport that logs info to stdout and errors stderr */
  12. cli.prototype.name = 'cli';
  13. function cli(options) {
  14. cli.__super__.constructor.call(this, options);
  15. this.quiet = options.quiet || false;
  16. }
  17. cli.prototype.log = function(info, callback) {
  18. var c, key, level, message, meta, pval, ref, stack, value;
  19. level = info.level, message = info.message;
  20. meta = (ref = info.meta) != null ? ref : {};
  21. if (level === 'error') {
  22. process.stderr.write("\n " + (chalk.red('error')) + " " + message + "\n");
  23. if (this.level === 'verbose' && (meta != null)) {
  24. if (meta.stack != null) {
  25. stack = meta.stack.substr(meta.stack.indexOf('\n') + 1);
  26. process.stderr.write(stack + "\n\n");
  27. }
  28. for (key in meta) {
  29. value = meta[key];
  30. if (key === 'message' || key === 'stack') {
  31. continue;
  32. }
  33. pval = util.inspect(value, false, 2, true).replace(/\n/g, '\n ');
  34. process.stderr.write(" " + key + ": " + pval + "\n");
  35. }
  36. } else {
  37. process.stderr.write("\n");
  38. }
  39. } else if (!this.quiet) {
  40. if (level !== 'info') {
  41. c = level === 'warn' ? 'yellow' : 'grey';
  42. message = (chalk[c](level)) + " " + message;
  43. }
  44. if (Object.keys(meta).length > 0) {
  45. message += util.format(' %j', meta);
  46. }
  47. process.stdout.write(" " + message + "\n");
  48. }
  49. this.emit('logged');
  50. return callback(null, true);
  51. };
  52. return cli;
  53. })(winston.Transport);
  54. transports = [
  55. new cli({
  56. level: 'info'
  57. })
  58. ];
  59. logger = winston.createLogger({
  60. exitOnError: true,
  61. transports: transports
  62. });
  63. module.exports = {
  64. logger: logger,
  65. transports: transports
  66. };
  67. }).call(this);