File size: 1,499 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const isDevelopment = import.meta.env.MODE === 'development';
const isLoggerEnabled = import.meta.env.VITE_ENABLE_LOGGER === 'true';
const loggerFilter = import.meta.env.VITE_LOGGER_FILTER || '';

type LogFunction = (...args: unknown[]) => void;

const createLogFunction = (
  consoleMethod: LogFunction,
  type?: 'log' | 'warn' | 'error' | 'info' | 'debug' | 'dir',
): LogFunction => {
  return (...args: unknown[]) => {
    if (isDevelopment || isLoggerEnabled) {
      const tag = typeof args[0] === 'string' ? args[0] : '';
      if (shouldLog(tag)) {
        if (tag && typeof args[1] === 'string' && type === 'error') {
          consoleMethod(`[${tag}] ${args[1]}`, ...args.slice(2));
        } else if (tag && args.length > 1) {
          consoleMethod(`[${tag}]`, ...args.slice(1));
        } else {
          consoleMethod(...args);
        }
      }
    }
  };
};

const logger = {
  log: createLogFunction(console.log, 'log'),
  dir: createLogFunction(console.dir, 'dir'),
  warn: createLogFunction(console.warn, 'warn'),
  info: createLogFunction(console.info, 'info'),
  error: createLogFunction(console.error, 'error'),
  debug: createLogFunction(console.debug, 'debug'),
};

function shouldLog(tag: string): boolean {
  if (!loggerFilter) {
    return true;
  }
  /* If no tag is provided, always log */
  if (!tag) {
    return true;
  }
  return loggerFilter
    .split(',')
    .some((filter) => tag.toLowerCase().includes(filter.trim().toLowerCase()));
}

export default logger;