LoggingEvent.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const flatted = require('flatted');
  2. const levels = require('./levels');
  3. /**
  4. * @name LoggingEvent
  5. * @namespace Log4js
  6. */
  7. class LoggingEvent {
  8. /**
  9. * Models a logging event.
  10. * @constructor
  11. * @param {string} categoryName name of category
  12. * @param {Log4js.Level} level level of message
  13. * @param {Array} data objects to log
  14. * @author Seth Chisamore
  15. */
  16. constructor(categoryName, level, data, context, location) {
  17. this.startTime = new Date();
  18. this.categoryName = categoryName;
  19. this.data = data;
  20. this.level = level;
  21. this.context = Object.assign({}, context);
  22. this.pid = process.pid;
  23. if (location) {
  24. this.functionName = location.functionName;
  25. this.fileName = location.fileName;
  26. this.lineNumber = location.lineNumber;
  27. this.columnNumber = location.columnNumber;
  28. this.callStack = location.callStack;
  29. }
  30. }
  31. serialise() {
  32. const logData = this.data.map((e) => {
  33. // JSON.stringify(new Error('test')) returns {}, which is not really useful for us.
  34. // The following allows us to serialize errors correctly.
  35. if (e && e.message && e.stack) {
  36. e = Object.assign({ message: e.message, stack: e.stack }, e);
  37. }
  38. return e;
  39. });
  40. this.data = logData;
  41. return flatted.stringify(this);
  42. }
  43. static deserialise(serialised) {
  44. let event;
  45. try {
  46. const rehydratedEvent = flatted.parse(serialised);
  47. rehydratedEvent.data = rehydratedEvent.data.map((e) => {
  48. if (e && e.message && e.stack) {
  49. const fakeError = new Error(e);
  50. Object.keys(e).forEach((key) => { fakeError[key] = e[key]; });
  51. e = fakeError;
  52. }
  53. return e;
  54. });
  55. event = new LoggingEvent(
  56. rehydratedEvent.categoryName,
  57. levels.getLevel(rehydratedEvent.level.levelStr),
  58. rehydratedEvent.data,
  59. rehydratedEvent.context
  60. );
  61. event.startTime = new Date(rehydratedEvent.startTime);
  62. event.pid = rehydratedEvent.pid;
  63. event.cluster = rehydratedEvent.cluster;
  64. } catch (e) {
  65. event = new LoggingEvent(
  66. 'log4js',
  67. levels.ERROR,
  68. ['Unable to parse log:', serialised, 'because: ', e]
  69. );
  70. }
  71. return event;
  72. }
  73. }
  74. module.exports = LoggingEvent;