All files / src/utils logger.ts

86.95% Statements 20/23
61.11% Branches 11/18
70% Functions 7/10
86.36% Lines 19/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 6817x     17x                       17x 36x       36x         17x 28x 28x     17x 28x 28x       17x 17x 17x 17x 17x   17x                           28x                   17x  
import { getEnvVariable } from "./shared";
 
// Define log levels with corresponding priorities
const LOG_LEVELS = {
  error: 0, // Highest priority - critical errors
  warn: 1, // Warning messages
  info: 2, // General information
  debug: 3, // Debug information
} as const;
 
/**
 * Get the current log level from environment variables.
 * Defaults to 'info' if not set or invalid.
 * @returns {keyof typeof LOG_LEVELS} The current log level
 */
export const getLogLevel = (): keyof typeof LOG_LEVELS => {
  const envLevel = getEnvVariable(
    "COMPOSIO_LOGGING_LEVEL",
    "info"
  )?.toLowerCase();
  return envLevel && envLevel in LOG_LEVELS
    ? (envLevel as keyof typeof LOG_LEVELS)
    : "info";
};
 
const addTimestampToMessage = (message: string): string => {
  const timestamp = new Date().toISOString();
  return `${timestamp} - ${message}`;
};
 
const formatErrorMessage = (args: unknown[]): string => {
  return args
    .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : arg))
    .join(" ");
};
 
const getLogger = () => {
  const logger = console;
  const loggingLevel = getLogLevel();
  const logLevelValue = LOG_LEVELS[loggingLevel];
  const noop = () => {};
 
  return {
    error:
      logLevelValue >= LOG_LEVELS.error
        ? (...args: unknown[]) =>
            logger.error(addTimestampToMessage(formatErrorMessage(args)))
        : noop,
    warn:
      logLevelValue >= LOG_LEVELS.warn
        ? (...args: unknown[]) =>
            logger.warn(addTimestampToMessage(formatErrorMessage(args)))
        : noop,
    info:
      logLevelValue >= LOG_LEVELS.info
        ? (...args: unknown[]) =>
            logger.info(addTimestampToMessage(formatErrorMessage(args)))
        : noop,
    debug:
      logLevelValue >= LOG_LEVELS.debug
        ? (...args: unknown[]) =>
            logger.debug(addTimestampToMessage(formatErrorMessage(args)))
        : noop,
  };
};
 
export default getLogger();