aboutsummaryrefslogtreecommitdiff
path: root/node_modules/consola/src/consola.js
blob: 205b4ad5cb60b7e9ce72ecda4299ec28d763d7ab (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import types from './types'

export default class Consola {
  constructor (options = {}) {
    this.reporters = options.reporters || []
    this.types = Object.assign({}, types, options.types)
    this.level = options.level != null ? options.level : 3

    Object.assign(this, this.withDefaults())
  }

  withDefaults (defaults) {
    const logger = {}
    for (const type in this.types) {
      logger[type] = this._createLogFn(Object.assign({ type }, this.types[type], defaults))
    }
    return logger
  }

  _createLogFn (defaults) {
    return (opts, ...args) => {
      if (!opts) {
        return this
      }

      const logObj = Object.assign({
        date: new Date()
      }, defaults)

      const argsStr = Array.from(args).map(String).join(' ')

      if (typeof opts === 'string') {
        // String
        logObj.message = opts
        logObj.additional = argsStr
      } else if (opts.stack) {
        // Error
        const [message, ...stack] = opts.stack.split('\n')
        logObj.message = message
        logObj.additional = (argsStr.length ? argsStr + '\n' : '') + stack.map(s => s.trim()).join('\n')
      } else {
        // Object
        Object.assign(logObj, opts)
      }

      this._log(logObj)

      return this
    }
  }

  _log (logObj) {
    if (logObj.level > this.level) {
      return
    }
    for (const reporter of this.reporters) {
      reporter.log(logObj)
    }
    return this
  }

  add (reporter) {
    this.reporters.push(reporter)
    return this
  }

  clear () {
    this.reporters.splice(0)
    return this
  }

  remove (reporter) {
    const i = this.reporters.indexOf(reporter)
    if (i >= 0) {
      return this.reporters.splice(i, 1)
    }
    return this
  }

  withScope (scope) {
    return this.withDefaults({ scope })
  }
}

// Upward compatibility support to >= v2
Consola.prototype.addReporter = Consola.prototype.add

Consola.prototype.removeReporter = Consola.prototype.remove
Consola.prototype.removeReporter = Consola.prototype.clear

Consola.prototype.withTag = Consola.prototype.withScope