index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. * project - module
  3. * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
  4. * MIT Licensed
  5. */
  6. 'use strict';
  7. /**
  8. * Module dependencies.
  9. */
  10. var os = require('os');
  11. var util = require('util');
  12. var utility = require('utility');
  13. /**
  14. * Expose `formater`
  15. */
  16. module.exports = text;
  17. text.json = json;
  18. text.both = both;
  19. function text(err) {
  20. var infos = json(err);
  21. return format(infos);
  22. }
  23. function both(err) {
  24. var infos = json(err);
  25. var text = format(infos);
  26. return {
  27. text: text,
  28. json: infos
  29. }
  30. }
  31. function json(err) {
  32. if (!(err instanceof Error)) throw new TypeError('input non-error object: ' + err);
  33. var infos = {
  34. name: err.name,
  35. message: err.message,
  36. url: err.url || '',
  37. data: err.data || '',
  38. pid: process.pid,
  39. code: err.code
  40. };
  41. if (err.name === 'Error' && typeof err.code === 'string') {
  42. infos.name = err.code + err.name;
  43. }
  44. if (err.host) {
  45. infos.host = err.host;
  46. infos.message += ' (' + infos.host + ')';
  47. }
  48. infos.domainThrown = !!(err.domain_thrown || err.domainThrown);
  49. infos.name = infos.name + 'Exception';
  50. infos.time = utility.logDate();
  51. infos.hostname = os.hostname();
  52. // name and stack could not be change on node 0.11+
  53. var errName = err.name;
  54. var errStack = err.stack || 'no_stack';
  55. infos.stack = errName + ': ' + infos.message + '\n' + errStack.substring(errStack.indexOf('\n') + 1);
  56. return infos;
  57. }
  58. var formatTpl = '%s nodejs.%s: %s' + os.EOL +
  59. 'pid: %s' + os.EOL +
  60. 'domainThrown: %s' + os.EOL +
  61. 'Host: %s' + os.EOL +
  62. 'URL: %s' + os.EOL +
  63. 'Data: %j' + os.EOL +
  64. '%s';
  65. function format(infos) {
  66. return util.format(formatTpl,
  67. infos.time,
  68. infos.name,
  69. infos.stack,
  70. infos.pid,
  71. infos.domainThrown,
  72. infos.hostname,
  73. infos.url,
  74. infos.data,
  75. infos.time
  76. );
  77. }