logger.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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' ? null : (() => {
  9. // Don't overwrite this value if it's already set.
  10. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  11. if (!('__WB_DISABLE_DEV_LOGS' in self)) {
  12. self.__WB_DISABLE_DEV_LOGS = false;
  13. }
  14. let inGroup = false;
  15. const methodToColorMap = {
  16. debug: `#7f8c8d`,
  17. log: `#2ecc71`,
  18. warn: `#f39c12`,
  19. error: `#c0392b`,
  20. groupCollapsed: `#3498db`,
  21. groupEnd: null,
  22. };
  23. const print = function (method, args) {
  24. if (self.__WB_DISABLE_DEV_LOGS) {
  25. return;
  26. }
  27. if (method === 'groupCollapsed') {
  28. // Safari doesn't print all console.groupCollapsed() arguments:
  29. // https://bugs.webkit.org/show_bug.cgi?id=182754
  30. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  31. console[method](...args);
  32. return;
  33. }
  34. }
  35. const styles = [
  36. `background: ${methodToColorMap[method]}`,
  37. `border-radius: 0.5em`,
  38. `color: white`,
  39. `font-weight: bold`,
  40. `padding: 2px 0.5em`,
  41. ];
  42. // When in a group, the workbox prefix is not displayed.
  43. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  44. console[method](...logPrefix, ...args);
  45. if (method === 'groupCollapsed') {
  46. inGroup = true;
  47. }
  48. if (method === 'groupEnd') {
  49. inGroup = false;
  50. }
  51. };
  52. const api = {};
  53. const loggerMethods = Object.keys(methodToColorMap);
  54. for (const key of loggerMethods) {
  55. const method = key;
  56. api[method] = (...args) => {
  57. print(method, args);
  58. };
  59. }
  60. return api;
  61. })());
  62. export { logger };