File size: 2,523 Bytes
330c0d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
import log4js from 'log4js'
import chalk from 'chalk'
import fs from 'node:fs'

/**
* 设置日志样式
*/
export default function setLog () {
  let file = './logs'
  let log_level = 'info'
  if (!fs.existsSync(file)) {
    fs.mkdirSync(file)
  }

  /** 调整error日志等级 */
  // log4js.levels.levels[5].level = Number.MAX_VALUE
  // log4js.levels.levels.sort((a, b) => a.level - b.level)

  log4js.configure({
    appenders: {
      console: {
        type: 'console',
        layout: {
          type: 'pattern',
          pattern: '%[[Server][%d{hh:mm:ss}][%4.4p]%] %m'
        }
      },
      command: {
        type: 'dateFile', // 可以是console,dateFile,file,Logstash等
        filename: 'logs/command', // 将会按照filename和pattern拼接文件名
        pattern: 'yyyy-MM-dd.log',
        numBackups: 15,
        alwaysIncludePattern: true,
        layout: {
          type: 'pattern',
          pattern: '[%d{hh:mm:ss}][%4.4p] %m'
        }
      },
      error: {
        type: 'file',
        filename: 'logs/error.log',
        alwaysIncludePattern: true,
        layout: {
          type: 'pattern',
          pattern: '[%d{hh:mm:ss}][%4.4p] %m'
        }
      }
    },
    categories: {
      default: { appenders: ['console'], level: log_level },
      command: { appenders: ['console', 'command'], level: 'info' },
      error: { appenders: ['console', 'command', 'error'], level: 'error' }
    }
  })

  const defaultLogger = log4js.getLogger('message')
  const commandLogger = log4js.getLogger('command')
  const errorLogger = log4js.getLogger('error')

  /* eslint-disable no-useless-call */
  /** 全局变量 logger */
  global.logger = {
    trace () {
      defaultLogger.trace.call(defaultLogger, ...arguments)
    },
    debug () {
      defaultLogger.debug.call(defaultLogger, ...arguments)
    },
    info () {
      defaultLogger.info.call(commandLogger, ...arguments)
    },
    // warn及以上的日志采用error策略
    warn () {
      commandLogger.warn.call(defaultLogger, ...arguments)
    },
    error () {
      errorLogger.error.call(errorLogger, ...arguments)
    },
    fatal () {
      errorLogger.fatal.call(errorLogger, ...arguments)
    },
    mark () {
      errorLogger.mark.call(commandLogger, ...arguments)
    }
  }

  logColor()
}

function logColor () {
  logger.chalk = chalk
  logger.red = chalk.red
  logger.green = chalk.green
  logger.yellow = chalk.yellow
  logger.blue = chalk.blue
  logger.magenta = chalk.magenta
  logger.cyan = chalk.cyan
}