LoggingEvent.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const CircularJSON = require('circular-json');
  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) {
  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. }
  24. serialise() {
  25. const logData = this.data.map((e) => {
  26. // JSON.stringify(new Error('test')) returns {}, which is not really useful for us.
  27. // The following allows us to serialize errors correctly.
  28. if (e && e.message && e.stack) {
  29. e = Object.assign({ message: e.message, stack: e.stack }, e);
  30. }
  31. return e;
  32. });
  33. this.data = logData;
  34. return CircularJSON.stringify(this);
  35. }
  36. static deserialise(serialised) {
  37. let event;
  38. try {
  39. const rehydratedEvent = CircularJSON.parse(serialised);
  40. rehydratedEvent.data = rehydratedEvent.data.map((e) => {
  41. if (e && e.message && e.stack) {
  42. const fakeError = new Error(e);
  43. Object.keys(e).forEach((key) => { fakeError[key] = e[key]; });
  44. e = fakeError;
  45. }
  46. return e;
  47. });
  48. event = new LoggingEvent(
  49. rehydratedEvent.categoryName,
  50. levels.getLevel(rehydratedEvent.level.levelStr),
  51. rehydratedEvent.data,
  52. rehydratedEvent.context
  53. );
  54. event.startTime = new Date(rehydratedEvent.startTime);
  55. event.pid = rehydratedEvent.pid;
  56. event.cluster = rehydratedEvent.cluster;
  57. } catch (e) {
  58. event = new LoggingEvent(
  59. 'log4js',
  60. levels.ERROR,
  61. ['Unable to parse log:', serialised, 'because: ', e]
  62. );
  63. }
  64. return event;
  65. }
  66. }
  67. module.exports = LoggingEvent;