logging.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { clamp, debounce } from "@sv443-network/userutils";
  2. import { showIconToast } from "../components/toast.js";
  3. import { MarkdownDialog } from "../components/MarkdownDialog.js";
  4. import { scriptInfo } from "../constants.js";
  5. import { setGlobalProp } from "../interface.js";
  6. import { LogLevel } from "../types.js";
  7. import { t } from "./translations.js";
  8. import { getFeature } from "../config.js";
  9. import packageJson from "../../package.json" with { type: "json" };
  10. //#region logging fns
  11. let curLogLevel = LogLevel.Info;
  12. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  13. const consPrefix = `[${scriptInfo.name}]`;
  14. const consPrefixDbg = `[${scriptInfo.name}/#DEBUG]`;
  15. /** Sets the current log level. 0 = Debug, 1 = Info */
  16. export function setLogLevel(level: LogLevel) {
  17. curLogLevel = level;
  18. setGlobalProp("logLevel", level);
  19. if(curLogLevel !== level)
  20. log("Set the log level to", LogLevel[level]);
  21. }
  22. /** Extracts the log level from the last item from spread arguments - returns 0 if the last item is not a number or too low or high */
  23. function getLogLevel(args: unknown[]): number {
  24. const minLogLvl = 0, maxLogLvl = 1;
  25. if(typeof args.at(-1) === "number")
  26. return clamp(
  27. args.splice(args.length - 1)[0] as number,
  28. minLogLvl,
  29. maxLogLvl,
  30. );
  31. return LogLevel.Debug;
  32. }
  33. /**
  34. * Logs all passed values to the console, as long as the log level is sufficient.
  35. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if it shouldn't be.
  36. */
  37. export function log(...args: unknown[]): void {
  38. if(curLogLevel <= getLogLevel(args))
  39. console.log(consPrefix, ...args);
  40. }
  41. /**
  42. * Logs all passed values to the console as info, as long as the log level is sufficient.
  43. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if it shouldn't be.
  44. */
  45. export function info(...args: unknown[]): void {
  46. if(curLogLevel <= getLogLevel(args))
  47. console.info(consPrefix, ...args);
  48. }
  49. /** Logs all passed values to the console as a warning, no matter the log level. */
  50. export function warn(...args: unknown[]): void {
  51. console.warn(consPrefix, ...args);
  52. }
  53. const showErrToast = debounce(
  54. (errName: string, ...args: unknown[]) =>
  55. showIconToast({
  56. message: t("generic_error_toast_encountered_error_type", errName),
  57. subtitle: t("generic_error_toast_click_for_details"),
  58. icon: "icon-error",
  59. iconFill: "var(--bytm-error-col)",
  60. onClick: () => getErrorDialog(errName, Array.isArray(args) ? args : []).open(),
  61. }),
  62. 1000,
  63. );
  64. /** Logs all passed values to the console as an error, no matter the log level. */
  65. export function error(...args: unknown[]): void {
  66. console.error(consPrefix, ...args);
  67. getFeature("showToastOnGenericError") && showErrToast(args.find(a => a instanceof Error)?.name ?? t("error"), ...args);
  68. }
  69. /** Logs all passed values to the console with a debug-specific prefix */
  70. export function dbg(...args: unknown[]): void {
  71. console.log(consPrefixDbg, ...args);
  72. }
  73. //#region error dialog
  74. function getErrorDialog(errName: string, args: unknown[]) {
  75. return new MarkdownDialog({
  76. id: "generic-error",
  77. height: 400,
  78. width: 500,
  79. small: true,
  80. destroyOnClose: true,
  81. renderHeader() {
  82. const header = document.createElement("h2");
  83. header.classList.add("bytm-dialog-title");
  84. header.role = "heading";
  85. header.ariaLevel = "1";
  86. header.tabIndex = 0;
  87. header.textContent = header.ariaLabel = errName;
  88. return header;
  89. },
  90. body: `\
  91. ${args.length > 0 ? args.join(" ") : t("generic_error_dialog_message")}
  92. ${t("generic_error_dialog_open_console_note", consPrefix, packageJson.bugs.url)}`,
  93. });
  94. }
  95. //#region error classes
  96. export class CustomError extends Error {
  97. public readonly time: number;
  98. constructor(name: string, message: string, opts?: ErrorOptions) {
  99. super(message, opts);
  100. this.name = name;
  101. this.time = Date.now();
  102. }
  103. }
  104. export class LyricsError extends CustomError {
  105. constructor(message: string, opts?: ErrorOptions) {
  106. super("LyricsError", message, opts);
  107. }
  108. }
  109. export class PluginError extends CustomError {
  110. constructor(message: string, opts?: ErrorOptions) {
  111. super("PluginError", message, opts);
  112. }
  113. }