logger.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const LOG_PREFIX = "PeerJS: ";
  2. /*
  3. Prints log messages depending on the debug level passed in. Defaults to 0.
  4. 0 Prints no logs.
  5. 1 Prints only errors.
  6. 2 Prints errors and warnings.
  7. 3 Prints all logs.
  8. */
  9. export enum LogLevel {
  10. /**
  11. * Prints no logs.
  12. */
  13. Disabled,
  14. /**
  15. * Prints only errors.
  16. */
  17. Errors,
  18. /**
  19. * Prints errors and warnings.
  20. */
  21. Warnings,
  22. /**
  23. * Prints all logs.
  24. */
  25. All,
  26. }
  27. class Logger {
  28. private _logLevel = LogLevel.Disabled;
  29. get logLevel(): LogLevel {
  30. return this._logLevel;
  31. }
  32. set logLevel(logLevel: LogLevel) {
  33. this._logLevel = logLevel;
  34. }
  35. log(...args: any[]) {
  36. if (this._logLevel >= LogLevel.All) {
  37. this._print(LogLevel.All, ...args);
  38. }
  39. }
  40. warn(...args: any[]) {
  41. if (this._logLevel >= LogLevel.Warnings) {
  42. this._print(LogLevel.Warnings, ...args);
  43. }
  44. }
  45. error(...args: any[]) {
  46. if (this._logLevel >= LogLevel.Errors) {
  47. this._print(LogLevel.Errors, ...args);
  48. }
  49. }
  50. setLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {
  51. this._print = fn;
  52. }
  53. private _print(logLevel: LogLevel, ...rest: any[]): void {
  54. const copy = [LOG_PREFIX, ...rest];
  55. for (const i in copy) {
  56. if (copy[i] instanceof Error) {
  57. copy[i] = "(" + copy[i].name + ") " + copy[i].message;
  58. }
  59. }
  60. if (logLevel >= LogLevel.All) {
  61. console.log(...copy);
  62. } else if (logLevel >= LogLevel.Warnings) {
  63. console.warn("WARNING", ...copy);
  64. } else if (logLevel >= LogLevel.Errors) {
  65. console.error("ERROR", ...copy);
  66. }
  67. }
  68. }
  69. export default new Logger();