保誠-保戶業務員媒合平台
tomasysh
2022-05-25 43d0eed31f4b2a59e23c06ceba3616aac3f549f6
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
import util from 'util'
import { parseStack } from '../utils/error'
import { writeStream } from '../utils/stream'
import { formatDate } from '../utils/date'
 
const DEFAULTS = {
  dateFormat: 'HH:mm:ss',
  formatOptions: {
    date: true,
    colors: false,
    compact: true
  }
}
 
const bracket = x => x ? `[${x}]` : ''
 
export default class BasicReporter {
  constructor (options) {
    this.options = Object.assign({}, DEFAULTS, options)
  }
 
  formatStack (stack) {
    return '  ' + parseStack(stack).join('\n  ')
  }
 
  formatArgs (args) {
    const _args = args.map(arg => {
      if (arg && typeof arg.stack === 'string') {
        return arg.message + '\n' + this.formatStack(arg.stack)
      }
      return arg
    })
 
    // Only supported with Node >= 10
    // https://nodejs.org/api/util.html#util_util_inspect_object_options
    if (typeof util.formatWithOptions === 'function') {
      return util.formatWithOptions(this.options.formatOptions, ..._args)
    } else {
      return util.format(..._args)
    }
  }
 
  formatDate (date) {
    return this.options.formatOptions.date ? formatDate(this.options.dateFormat, date) : ''
  }
 
  filterAndJoin (arr) {
    return arr.filter(x => x).join(' ')
  }
 
  formatLogObj (logObj) {
    const message = this.formatArgs(logObj.args)
 
    return this.filterAndJoin([
      bracket(logObj.type),
      bracket(logObj.tag),
      message
    ])
  }
 
  log (logObj, { async, stdout, stderr } = {}) {
    const line = this.formatLogObj(logObj, {
      width: stdout.columns || 0
    })
 
    return writeStream(
      line + '\n',
      logObj.level < 2 ? stderr : stdout,
      async ? 'async' : 'default'
    )
  }
}