log.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /** @typedef {"info" | "warning" | "error"} LogLevel */
  2. /** @type {LogLevel} */
  3. var logLevel = "info";
  4. function dummy() {}
  5. /**
  6. * @param {LogLevel} level log level
  7. * @returns {boolean} true, if should log
  8. */
  9. function shouldLog(level) {
  10. var shouldLog =
  11. (logLevel === "info" && level === "info") ||
  12. (["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") ||
  13. (["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error");
  14. return shouldLog;
  15. }
  16. /**
  17. * @param {(msg?: string) => void} logFn log function
  18. * @returns {(level: LogLevel, msg?: string) => void} function that logs when log level is sufficient
  19. */
  20. function logGroup(logFn) {
  21. return function (level, msg) {
  22. if (shouldLog(level)) {
  23. logFn(msg);
  24. }
  25. };
  26. }
  27. /**
  28. * @param {LogLevel} level log level
  29. * @param {string|Error} msg message
  30. */
  31. module.exports = function (level, msg) {
  32. if (shouldLog(level)) {
  33. if (level === "info") {
  34. console.log(msg);
  35. } else if (level === "warning") {
  36. console.warn(msg);
  37. } else if (level === "error") {
  38. console.error(msg);
  39. }
  40. }
  41. };
  42. var group = console.group || dummy;
  43. var groupCollapsed = console.groupCollapsed || dummy;
  44. var groupEnd = console.groupEnd || dummy;
  45. module.exports.group = logGroup(group);
  46. module.exports.groupCollapsed = logGroup(groupCollapsed);
  47. module.exports.groupEnd = logGroup(groupEnd);
  48. /**
  49. * @param {LogLevel} level log level
  50. */
  51. module.exports.setLogLevel = function (level) {
  52. logLevel = level;
  53. };
  54. /**
  55. * @param {Error} err error
  56. * @returns {string} formatted error
  57. */
  58. module.exports.formatError = function (err) {
  59. var message = err.message;
  60. var stack = err.stack;
  61. if (!stack) {
  62. return message;
  63. } else if (stack.indexOf(message) < 0) {
  64. return message + "\n" + stack;
  65. } else {
  66. return stack;
  67. }
  68. };