Add log function
This commit is contained in:
0
src/gitea.ts
Normal file
0
src/gitea.ts
Normal file
@@ -0,0 +1 @@
|
||||
import { log } from './logger'
|
||||
|
||||
39
src/logger.ts
Normal file
39
src/logger.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
|
||||
const colours: Record<LogLevel, string> = {
|
||||
DEBUG: '\x1b[36m', // Cyan
|
||||
INFO: '\x1b[32m', // Green
|
||||
WARN: '\x1b[33m', // Yellow
|
||||
ERROR: '\x1b[31m', // Red
|
||||
};
|
||||
|
||||
const levelWeight: Record<LogLevel, number> = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3,
|
||||
};
|
||||
|
||||
const RESET = '\x1b[0m';
|
||||
|
||||
const CURRENT_LOG_LEVEL = (process.env.LOG_LEVEL as LogLevel) || 'INFO';
|
||||
const MIN_WEIGHT = levelWeight[CURRENT_LOG_LEVEL] ?? 1;
|
||||
|
||||
export function log(level: LogLevel, msg: string, ...args: any[]): void {
|
||||
// Drop log if below LOG_LEVEL
|
||||
if (levelWeight[level] < MIN_WEIGHT) return;
|
||||
|
||||
const timestamp = new Date().toISOString();
|
||||
const colour = colours[level] || RESET;
|
||||
|
||||
const header = `[${timestamp}] [${colour}${level.padEnd(5)}${RESET}]: ${msg}`;
|
||||
|
||||
if (args.length > 0) {
|
||||
if (level === 'ERROR') {
|
||||
console.error(header, ...args);
|
||||
} else {
|
||||
console.log(header, ...args);
|
||||
}
|
||||
} else {
|
||||
level === 'ERROR' ? console.error(header) : console.log(header);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user