logger.mjs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.mjs';
  8. const logger = process.env.NODE_ENV === 'production' ? null : (() => {
  9. let inGroup = false;
  10. const methodToColorMap = {
  11. debug: `#7f8c8d`, // Gray
  12. log: `#2ecc71`, // Green
  13. warn: `#f39c12`, // Yellow
  14. error: `#c0392b`, // Red
  15. groupCollapsed: `#3498db`, // Blue
  16. groupEnd: null, // No colored prefix on groupEnd
  17. };
  18. const print = function(method, args) {
  19. if (method === 'groupCollapsed') {
  20. // Safari doesn't print all console.groupCollapsed() arguments:
  21. // https://bugs.webkit.org/show_bug.cgi?id=182754
  22. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  23. console[method](...args);
  24. return;
  25. }
  26. }
  27. const styles = [
  28. `background: ${methodToColorMap[method]}`,
  29. `border-radius: 0.5em`,
  30. `color: white`,
  31. `font-weight: bold`,
  32. `padding: 2px 0.5em`,
  33. ];
  34. // When in a group, the workbox prefix is not displayed.
  35. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  36. console[method](...logPrefix, ...args);
  37. if (method === 'groupCollapsed') {
  38. inGroup = true;
  39. }
  40. if (method === 'groupEnd') {
  41. inGroup = false;
  42. }
  43. };
  44. const api = {};
  45. for (const method of Object.keys(methodToColorMap)) {
  46. api[method] = (...args) => {
  47. print(method, args);
  48. };
  49. }
  50. return api;
  51. })();
  52. export {logger};