All files / src/lib logger.ts

100% Statements 35/35
93.1% Branches 27/29
100% Functions 8/8
100% Lines 35/35

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                            1x 1x   1x   28x 28x 23x 23x   16x 16x 16x 16x   1x 1x 13x 13x 13x 1x 7x 7x 7x 1x 4x 4x 4x 1x 4x 4x 4x 1x   1x 26x 26x   1x 17x 17x  
/**
 * Lightweight logger for opensip-tools.
 * Replaces @opensip/core/logger — wraps console with level filtering.
 * Accepts both string and structured object arguments for compatibility
 * with checks copied from the opensip monorepo.
 */
 
export interface Logger {
  debug(msgOrObj: string | Record<string, unknown>, data?: Record<string, unknown>): void;
  info(msgOrObj: string | Record<string, unknown>, data?: Record<string, unknown>): void;
  warn(msgOrObj: string | Record<string, unknown>, data?: Record<string, unknown>): void;
  error(msgOrObj: string | Record<string, unknown>, data?: Record<string, unknown>): void;
}
 
let currentLevel: 'debug' | 'info' | 'warn' | 'error' = 'warn';
let silent = false;
 
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 } as const;
 
function shouldLog(level: keyof typeof LEVELS): boolean {
  if (silent) return false;
  return LEVELS[level] >= LEVELS[currentLevel];
}
 
function formatMsg(msgOrObj: string | Record<string, unknown>): string {
  if (typeof msgOrObj === 'string') return msgOrObj;
  return (msgOrObj.msg as string) ?? (msgOrObj.evt as string) ?? JSON.stringify(msgOrObj);
}
 
export const logger: Logger = {
  debug(msgOrObj, data) {
    if (!shouldLog('debug')) return;
    data ? console.debug(formatMsg(msgOrObj), data) : console.debug(formatMsg(msgOrObj));
  },
  info(msgOrObj, data) {
    if (!shouldLog('info')) return;
    data ? console.info(formatMsg(msgOrObj), data) : console.info(formatMsg(msgOrObj));
  },
  warn(msgOrObj, data) {
    if (!shouldLog('warn')) return;
    data ? console.warn(formatMsg(msgOrObj), data) : console.warn(formatMsg(msgOrObj));
  },
  error(msgOrObj, data) {
    if (!shouldLog('error')) return;
    data ? console.error(formatMsg(msgOrObj), data) : console.error(formatMsg(msgOrObj));
  },
};
 
export function setLogLevel(level: 'debug' | 'info' | 'warn' | 'error'): void {
  currentLevel = level;
}
 
export function setSilent(value: boolean): void {
  silent = value;
}