Home Reference Source

src/utils/logger.ts

  1. interface ILogFunction {
  2. (message?: any, ...optionalParams: any[]): void;
  3. }
  4.  
  5. interface ILogger {
  6. trace: ILogFunction;
  7. debug: ILogFunction;
  8. log: ILogFunction;
  9. warn: ILogFunction;
  10. info: ILogFunction;
  11. error: ILogFunction;
  12. }
  13.  
  14. const noop: ILogFunction = function () {};
  15.  
  16. const fakeLogger: ILogger = {
  17. trace: noop,
  18. debug: noop,
  19. log: noop,
  20. warn: noop,
  21. info: noop,
  22. error: noop,
  23. };
  24.  
  25. let exportedLogger: ILogger = fakeLogger;
  26.  
  27. // let lastCallTime;
  28. // function formatMsgWithTimeInfo(type, msg) {
  29. // const now = Date.now();
  30. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  31. // lastCallTime = now;
  32. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  33. // return msg;
  34. // }
  35.  
  36. function consolePrintFn(type: string): ILogFunction {
  37. const func: ILogFunction = self.console[type];
  38. if (func) {
  39. return func.bind(self.console, `[${type}] >`);
  40. }
  41. return noop;
  42. }
  43.  
  44. function exportLoggerFunctions(
  45. debugConfig: boolean | ILogger,
  46. ...functions: string[]
  47. ): void {
  48. functions.forEach(function (type) {
  49. exportedLogger[type] = debugConfig[type]
  50. ? debugConfig[type].bind(debugConfig)
  51. : consolePrintFn(type);
  52. });
  53. }
  54.  
  55. export function enableLogs(debugConfig: boolean | ILogger): void {
  56. // check that console is available
  57. if (
  58. (self.console && debugConfig === true) ||
  59. typeof debugConfig === 'object'
  60. ) {
  61. exportLoggerFunctions(
  62. debugConfig,
  63. // Remove out from list here to hard-disable a log-level
  64. // 'trace',
  65. 'debug',
  66. 'log',
  67. 'info',
  68. 'warn',
  69. 'error'
  70. );
  71. // Some browsers don't allow to use bind on console object anyway
  72. // fallback to default if needed
  73. try {
  74. exportedLogger.log();
  75. } catch (e) {
  76. exportedLogger = fakeLogger;
  77. }
  78. } else {
  79. exportedLogger = fakeLogger;
  80. }
  81. }
  82.  
  83. export const logger: ILogger = exportedLogger;