log.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var logLevel = "info";
  2. function dummy() {}
  3. function shouldLog(level) {
  4. var shouldLog =
  5. (logLevel === "info" && level === "info") ||
  6. (["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") ||
  7. (["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error");
  8. return shouldLog;
  9. }
  10. function logGroup(logFn) {
  11. return function (level, msg) {
  12. if (shouldLog(level)) {
  13. logFn(msg);
  14. }
  15. };
  16. }
  17. module.exports = function (level, msg) {
  18. if (shouldLog(level)) {
  19. if (level === "info") {
  20. console.log(msg);
  21. } else if (level === "warning") {
  22. console.warn(msg);
  23. } else if (level === "error") {
  24. console.error(msg);
  25. }
  26. }
  27. };
  28. /* eslint-disable node/no-unsupported-features/node-builtins */
  29. var group = console.group || dummy;
  30. var groupCollapsed = console.groupCollapsed || dummy;
  31. var groupEnd = console.groupEnd || dummy;
  32. /* eslint-enable node/no-unsupported-features/node-builtins */
  33. module.exports.group = logGroup(group);
  34. module.exports.groupCollapsed = logGroup(groupCollapsed);
  35. module.exports.groupEnd = logGroup(groupEnd);
  36. module.exports.setLogLevel = function (level) {
  37. logLevel = level;
  38. };
  39. module.exports.formatError = function (err) {
  40. var message = err.message;
  41. var stack = err.stack;
  42. if (!stack) {
  43. return message;
  44. } else if (stack.indexOf(message) < 0) {
  45. return message + "\n" + stack;
  46. } else {
  47. return stack;
  48. }
  49. };