Logger.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import Codes from "./enum/Codes.js"
  2. import {reporter} from "./Reporter.js"
  3. import util from "./util.js"
  4. export default class Logger{
  5. constructor(e) {
  6. this.level = 3
  7. this.module = e
  8. }
  9. static setLevel(e) {
  10. this.level = e
  11. }
  12. setLevel(e) {
  13. this.level = e
  14. }
  15. atleast(e) {
  16. return e >= this.level && e >= this.level
  17. }
  18. print(e, t, ...r) {
  19. if (this.atleast(t)) {
  20. const n = e == "debug" ? "info" : e
  21. , o = this.prefix(e);
  22. console[n].call(null, o, ...r)
  23. }
  24. if (e !== "debug" && e !== "info") {
  25. const n = r.map(o=>{
  26. if (o instanceof Object)
  27. try {
  28. return JSON.stringify(o)
  29. } catch {
  30. return o
  31. }
  32. else
  33. return o
  34. }
  35. ).join(",");
  36. reporter.report("log", {
  37. message: n,
  38. level: e,
  39. module: this.module
  40. })
  41. }
  42. }
  43. debug(...e) {
  44. return this.print("debug", 1, ...e)
  45. }
  46. info(...e) {
  47. return this.print("info", 2, ...e)
  48. }
  49. infoAndReportLog(e, ...t) {
  50. const {reportOptions: r} = e;
  51. delete e.reportOptions,
  52. reporter.report("log", e, r),
  53. t.length || (t = [e.message]),
  54. this.debug(...t)
  55. }
  56. infoAndReportMeasurement(e, ...t) {
  57. var n;
  58. const {reportOptions: r} = e;
  59. if (e.startTime) {
  60. const o = Date.now();
  61. e.value === void 0 && (e.endTime = o),
  62. e.value === void 0 && (e.value = o - e.startTime)
  63. }
  64. if (e.error ? e.code = ((n = e.error) == null ? void 0 : n.code) || Codes.Internal : e.code = Codes.Success,
  65. reporter.report("measurement", e, r),
  66. t.length || (t = [e]),
  67. e.level === 4 || e.error) {
  68. this.error(...t);
  69. return
  70. }
  71. this.warn(...t)
  72. }
  73. warn(...e) {
  74. return this.print("warn", 3, ...e)
  75. }
  76. error(...e) {
  77. return this.print("error", 4, ...e)
  78. }
  79. prefix(e) {
  80. return `[${this.module}][${e}] ${util.getFormattedDate(new Date)}:`
  81. }
  82. };