aboutsummaryrefslogtreecommitdiff
path: root/node_modules/loglevelnext/factory/PrefixFactory.js
blob: 0f2c397589b23bc7eb9c0c74a86c2b73b1ea7c84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict';

const MethodFactory = require('../lib/MethodFactory');

const defaults = {
  level: opts => `[${opts.level}]`,
  name: opts => opts.logger.name,
  template: '{{time}} {{level}} ',
  time: () => new Date().toTimeString().split(' ')[0]
};

module.exports = class PrefixFactory extends MethodFactory {
  constructor(logger, options) {
    super(logger);
    this.options = Object.assign({}, defaults, options);
  }

  interpolate(level) {
    return this.options.template.replace(/{{([^{}]*)}}/g, (stache, prop) => {
      const fn = this.options[prop];

      if (fn) {
        return fn({ level, logger: this.logger });
      }

      return stache;
    });
  }

  make(methodName) {
    const og = super.make(methodName);

    return (...args) => {
      const output = this.interpolate(methodName);
      const [first] = args;

      if (typeof first === 'string') {
        args[0] = output + first;
      } else {
        args.unshift(output);
      }

      og(...args);
    };
  }
};