basic.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import util from 'util'
  2. import { parseStack } from '../utils/error'
  3. import { writeStream } from '../utils/stream'
  4. import { formatDate } from '../utils/date'
  5. const DEFAULTS = {
  6. dateFormat: 'HH:mm:ss',
  7. formatOptions: {
  8. date: true,
  9. colors: false,
  10. compact: true
  11. }
  12. }
  13. const bracket = x => x ? `[${x}]` : ''
  14. export default class BasicReporter {
  15. constructor (options) {
  16. this.options = Object.assign({}, DEFAULTS, options)
  17. }
  18. formatStack (stack) {
  19. return ' ' + parseStack(stack).join('\n ')
  20. }
  21. formatArgs (args) {
  22. const _args = args.map(arg => {
  23. if (arg && typeof arg.stack === 'string') {
  24. return arg.message + '\n' + this.formatStack(arg.stack)
  25. }
  26. return arg
  27. })
  28. // Only supported with Node >= 10
  29. // https://nodejs.org/api/util.html#util_util_inspect_object_options
  30. if (typeof util.formatWithOptions === 'function') {
  31. return util.formatWithOptions(this.options.formatOptions, ..._args)
  32. } else {
  33. return util.format(..._args)
  34. }
  35. }
  36. formatDate (date) {
  37. return this.options.formatOptions.date ? formatDate(this.options.dateFormat, date) : ''
  38. }
  39. filterAndJoin (arr) {
  40. return arr.filter(x => x).join(' ')
  41. }
  42. formatLogObj (logObj) {
  43. const message = this.formatArgs(logObj.args)
  44. return this.filterAndJoin([
  45. bracket(logObj.type),
  46. bracket(logObj.tag),
  47. message
  48. ])
  49. }
  50. log (logObj, { async, stdout, stderr } = {}) {
  51. const line = this.formatLogObj(logObj, {
  52. width: stdout.columns || 0
  53. })
  54. return writeStream(
  55. line + '\n',
  56. logObj.level < 2 ? stderr : stdout,
  57. async ? 'async' : 'default'
  58. )
  59. }
  60. }