metadata.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const format = require('./format');
  3. function fillExcept(info, fillExceptKeys, metadataKey) {
  4. const savedKeys = fillExceptKeys.reduce((acc, key) => {
  5. acc[key] = info[key];
  6. delete info[key];
  7. return acc;
  8. }, {});
  9. const metadata = Object.keys(info).reduce((acc, key) => {
  10. acc[key] = info[key];
  11. delete info[key];
  12. return acc;
  13. }, {});
  14. Object.assign(info, savedKeys, {
  15. [metadataKey]: metadata
  16. });
  17. return info;
  18. }
  19. function fillWith(info, fillWithKeys, metadataKey) {
  20. info[metadataKey] = fillWithKeys.reduce((acc, key) => {
  21. acc[key] = info[key];
  22. delete info[key];
  23. return acc;
  24. }, {});
  25. return info;
  26. }
  27. /**
  28. * Adds in a "metadata" object to collect extraneous data, similar to the metadata
  29. * object in winston 2.x.
  30. */
  31. module.exports = format((info, opts = {}) => {
  32. let metadataKey = 'metadata';
  33. if (opts.key) {
  34. metadataKey = opts.key;
  35. }
  36. let fillExceptKeys = [];
  37. if (!opts.fillExcept && !opts.fillWith) {
  38. fillExceptKeys.push('level');
  39. fillExceptKeys.push('message');
  40. }
  41. if (opts.fillExcept) {
  42. fillExceptKeys = opts.fillExcept;
  43. }
  44. if (fillExceptKeys.length > 0) {
  45. return fillExcept(info, fillExceptKeys, metadataKey);
  46. }
  47. if (opts.fillWith) {
  48. return fillWith(info, opts.fillWith, metadataKey);
  49. }
  50. return info;
  51. });