index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const utils_1 = require("../utils/utils");
  4. const code_1 = require("../const/code");
  5. const cloudbase_1 = require("../cloudbase");
  6. /**
  7. *
  8. *
  9. * @class Log
  10. */
  11. class Log {
  12. constructor() {
  13. const { _SCF_TCB_LOG } = cloudbase_1.CloudBase.getCloudbaseContext();
  14. this.src = 'app';
  15. this.isSupportClsReport = true;
  16. if (`${_SCF_TCB_LOG}` !== '1') {
  17. this.isSupportClsReport = false;
  18. }
  19. else if (!console.__baseLog__) {
  20. this.isSupportClsReport = false;
  21. }
  22. if (!this.isSupportClsReport) {
  23. // 当前非tcb scf环境 log功能会退化为console
  24. console.warn('请检查您是否在本地环境 或者 未开通高级日志功能,当前环境下无法上报cls日志,默认使用console');
  25. }
  26. }
  27. /**
  28. *
  29. *
  30. * @param {*} logMsg
  31. * @param {*} logLevel
  32. * @returns
  33. * @memberof Log
  34. */
  35. transformMsg(logMsg) {
  36. // 目前logMsg只支持字符串value且不支持多级, 加一层转换处理
  37. let realMsg = {};
  38. realMsg = Object.assign({}, realMsg, logMsg);
  39. return realMsg;
  40. }
  41. /**
  42. *
  43. *
  44. * @param {*} logMsg
  45. * @param {*} logLevel
  46. * @memberof Log
  47. */
  48. baseLog(logMsg, logLevel) {
  49. // 判断当前是否属于tcb scf环境
  50. if (Object.prototype.toString.call(logMsg).slice(8, -1) !== 'Object') {
  51. throw utils_1.E(Object.assign({}, code_1.ERROR.INVALID_PARAM, { message: 'log msg must be an object' }));
  52. }
  53. const msgContent = this.transformMsg(logMsg);
  54. if (this.isSupportClsReport) {
  55. ;
  56. console.__baseLog__(msgContent, logLevel);
  57. }
  58. else {
  59. if (console[logLevel]) {
  60. console[logLevel](msgContent);
  61. }
  62. }
  63. }
  64. /**
  65. *
  66. *
  67. * @param {*} logMsg
  68. * @memberof Log
  69. */
  70. log(logMsg) {
  71. this.baseLog(logMsg, 'log');
  72. }
  73. /**
  74. *
  75. *
  76. * @param {*} logMsg
  77. * @memberof Log
  78. */
  79. info(logMsg) {
  80. this.baseLog(logMsg, 'info');
  81. }
  82. /**
  83. *
  84. *
  85. * @param {*} logMsg
  86. * @memberof Log
  87. */
  88. error(logMsg) {
  89. this.baseLog(logMsg, 'error');
  90. }
  91. /**
  92. *
  93. *
  94. * @param {*} logMsg
  95. * @memberof Log
  96. */
  97. warn(logMsg) {
  98. this.baseLog(logMsg, 'warn');
  99. }
  100. }
  101. exports.Log = Log;
  102. function logger() {
  103. return new Log();
  104. }
  105. exports.logger = logger;