logger.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. Disabled,
  11. Errors,
  12. Warnings,
  13. All,
  14. }
  15. class Logger {
  16. private _logLevel = LogLevel.Disabled;
  17. get logLevel(): LogLevel {
  18. return this._logLevel;
  19. }
  20. set logLevel(logLevel: LogLevel) {
  21. this._logLevel = logLevel;
  22. }
  23. log(...args: any[]) {
  24. if (this._logLevel >= LogLevel.All) {
  25. this._print(LogLevel.All, ...args);
  26. }
  27. }
  28. warn(...args: any[]) {
  29. if (this._logLevel >= LogLevel.Warnings) {
  30. this._print(LogLevel.Warnings, ...args);
  31. }
  32. }
  33. error(...args: any[]) {
  34. if (this._logLevel >= LogLevel.Errors) {
  35. this._print(LogLevel.Errors, ...args);
  36. }
  37. }
  38. setLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {
  39. this._print = fn;
  40. }
  41. private _print(logLevel: LogLevel, ...rest: any[]): void {
  42. const copy = [LOG_PREFIX, ...rest];
  43. for (let i in copy) {
  44. if (copy[i] instanceof Error) {
  45. copy[i] = "(" + copy[i].name + ") " + copy[i].message;
  46. }
  47. }
  48. if (logLevel >= LogLevel.All) {
  49. console.log(...copy);
  50. } else if (logLevel >= LogLevel.Warnings) {
  51. console.warn("WARNING", ...copy);
  52. } else if (logLevel >= LogLevel.Errors) {
  53. console.error("ERROR", ...copy);
  54. }
  55. }
  56. }
  57. export default new Logger();