logger.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import * as Sentry from "@sentry/react";
  2. import Cohere from "cohere-js";
  3. import { isEmpty } from "lodash";
  4. type LogFunction = (error: Error, tags?: { [key: string]: string }) => void;
  5. type LogFunctions = {
  6. [key in Sentry.Severity]: LogFunction;
  7. };
  8. type LogFunctionBuilder = (
  9. scope: string,
  10. severity: Sentry.Severity
  11. ) => LogFunction;
  12. const logFunctionBuilder: LogFunctionBuilder = (scope, severity) => (
  13. error,
  14. tags
  15. ) => {
  16. if (process.env.ENABLE_COHERE) {
  17. Cohere.getSessionUrl((sessionUrl) => {
  18. Sentry.withScope((sentryScope) => {
  19. sentryScope.setTag("scope", scope);
  20. sentryScope.setTag("cohere_link", sessionUrl);
  21. sentryScope.setLevel(severity);
  22. if (!isEmpty(tags)) {
  23. sentryScope.setTags(tags);
  24. }
  25. Sentry.captureException(error);
  26. });
  27. });
  28. } else {
  29. Sentry.withScope((sentryScope) => {
  30. sentryScope.setTag("scope", scope);
  31. sentryScope.setLevel(severity);
  32. if (!isEmpty(tags)) {
  33. sentryScope.setTags(tags);
  34. }
  35. Sentry.captureException(error);
  36. });
  37. }
  38. };
  39. function buildLogger(scope: string = "global") {
  40. const logFunctions = Object.values(Sentry.Severity).reduce<LogFunctions>(
  41. (acc, currentSeverity) => {
  42. if (typeof currentSeverity === "string") {
  43. acc[currentSeverity] = logFunctionBuilder(
  44. scope,
  45. Sentry.Severity.fromString(currentSeverity)
  46. );
  47. }
  48. return acc;
  49. },
  50. {} as LogFunctions
  51. );
  52. return logFunctions;
  53. }
  54. export default buildLogger;