logger.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2019 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import '../_version.js';
  8. const logger = (process.env.NODE_ENV === 'production'
  9. ? null
  10. : (() => {
  11. // Don't overwrite this value if it's already set.
  12. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  13. if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {
  14. self.__WB_DISABLE_DEV_LOGS = false;
  15. }
  16. let inGroup = false;
  17. const methodToColorMap = {
  18. debug: `#7f8c8d`,
  19. log: `#2ecc71`,
  20. warn: `#f39c12`,
  21. error: `#c0392b`,
  22. groupCollapsed: `#3498db`,
  23. groupEnd: null, // No colored prefix on groupEnd
  24. };
  25. const print = function (method, args) {
  26. if (self.__WB_DISABLE_DEV_LOGS) {
  27. return;
  28. }
  29. if (method === 'groupCollapsed') {
  30. // Safari doesn't print all console.groupCollapsed() arguments:
  31. // https://bugs.webkit.org/show_bug.cgi?id=182754
  32. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  33. console[method](...args);
  34. return;
  35. }
  36. }
  37. const styles = [
  38. `background: ${methodToColorMap[method]}`,
  39. `border-radius: 0.5em`,
  40. `color: white`,
  41. `font-weight: bold`,
  42. `padding: 2px 0.5em`,
  43. ];
  44. // When in a group, the workbox prefix is not displayed.
  45. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  46. console[method](...logPrefix, ...args);
  47. if (method === 'groupCollapsed') {
  48. inGroup = true;
  49. }
  50. if (method === 'groupEnd') {
  51. inGroup = false;
  52. }
  53. };
  54. // eslint-disable-next-line @typescript-eslint/ban-types
  55. const api = {};
  56. const loggerMethods = Object.keys(methodToColorMap);
  57. for (const key of loggerMethods) {
  58. const method = key;
  59. api[method] = (...args) => {
  60. print(method, args);
  61. };
  62. }
  63. return api;
  64. })());
  65. export { logger };