logger.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import * as Sentry from "@sentry/react";
  2. import { isEmpty } from "lodash";
  3. type LogFunction = (error: Error, tags?: { [key: string]: string }) => void;
  4. type LogFunctions = {
  5. [key in Sentry.Severity]: LogFunction;
  6. };
  7. type LogFunctionBuilder = (
  8. scope: string,
  9. severity: Sentry.Severity
  10. ) => LogFunction;
  11. const logFunctionBuilder: LogFunctionBuilder = (scope, severity) => (
  12. error,
  13. tags
  14. ) => {
  15. Sentry.withScope((sentryScope) => {
  16. sentryScope.setTag("scope", scope);
  17. sentryScope.setLevel(severity);
  18. if (!isEmpty(tags)) {
  19. sentryScope.setTags(tags);
  20. }
  21. Sentry.captureException(error);
  22. });
  23. };
  24. function buildLogger(scope: string = "global") {
  25. const logFunctions = Object.values(Sentry.Severity).reduce<LogFunctions>(
  26. (acc, currentSeverity) => {
  27. if (typeof currentSeverity === "string") {
  28. acc[currentSeverity] = logFunctionBuilder(
  29. scope,
  30. Sentry.Severity.Info
  31. );
  32. }
  33. return acc;
  34. },
  35. {} as LogFunctions
  36. );
  37. return logFunctions;
  38. }
  39. export default buildLogger;