PrefixFactory.js 1004 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const MethodFactory = require('../lib/MethodFactory');
  3. const defaults = {
  4. level: opts => `[${opts.level}]`,
  5. name: opts => opts.logger.name,
  6. template: '{{time}} {{level}} ',
  7. time: () => new Date().toTimeString().split(' ')[0]
  8. };
  9. module.exports = class PrefixFactory extends MethodFactory {
  10. constructor(logger, options) {
  11. super(logger);
  12. this.options = Object.assign({}, defaults, options);
  13. }
  14. interpolate(level) {
  15. return this.options.template.replace(/{{([^{}]*)}}/g, (stache, prop) => {
  16. const fn = this.options[prop];
  17. if (fn) {
  18. return fn({ level, logger: this.logger });
  19. }
  20. return stache;
  21. });
  22. }
  23. make(methodName) {
  24. const og = super.make(methodName);
  25. return (...args) => {
  26. const output = this.interpolate(methodName);
  27. const [first] = args;
  28. if (typeof first === 'string') {
  29. args[0] = output + first;
  30. } else {
  31. args.unshift(output);
  32. }
  33. og(...args);
  34. };
  35. }
  36. };