logger.ts 1.6 KB

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