logger.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * @Description: 日志工具函数
  3. * @Autor: kindring
  4. * @Date: 2021-12-14 14:07:17
  5. * @LastEditors: kindring
  6. * @LastEditTime: 2021-12-14 14:46:16
  7. * @LastDescript:
  8. */
  9. const Path = require('path');
  10. const log4js = require('log4js');
  11. levels = {
  12. 'trace': log4js.levels.TRACE,
  13. 'debug': log4js.levels.DEBUG,
  14. 'info': log4js.levels.INFO,
  15. 'warn': log4js.levels.WARN,
  16. 'error': log4js.levels.ERROR,
  17. 'fatal': log4js.levels.FATAL,
  18. }
  19. const logFileName = 'info.log';
  20. const _path = Path.resolve(__dirname, `log/${logFileName}`)
  21. console.log(_path);
  22. log4js.configure({
  23. // 输出到控制台的内容,同时也输出到日志文件中
  24. replaceConsole: true,
  25. appenders: {
  26. cheese: {
  27. // 设置类型为 dateFile
  28. type: 'dateFile',
  29. // 配置文件名
  30. filename: _path,
  31. // 指定编码格式为 utf-8
  32. encoding: 'utf-8',
  33. // 配置 layout,此处使用自定义模式 pattern
  34. // layout: 'basic',
  35. // 日志文件按日期(天)切割
  36. pattern: "yyyy-MM-dd",
  37. // 回滚旧的日志文件时,保证以 .log 结尾 (只有在 alwaysIncludePattern 为 false 生效)
  38. keepFileExt: true,
  39. // 输出的日志文件名是都始终包含 pattern 日期结尾
  40. alwaysIncludePattern: true,
  41. },
  42. console: {
  43. type: 'console'
  44. }
  45. },
  46. categories: {
  47. // 设置默认的 categories
  48. default: { appenders: ['cheese', 'console'], level: 'debug' },
  49. }
  50. })
  51. exports.logger = (name, level) => {
  52. const logger = log4js.getLogger(name)
  53. // 默认为debug权限及以上
  54. logger.level = levels[level] || levels['debug']
  55. return logger
  56. }