@cloud-copilot/iam-collect
Version:
Collect IAM information from AWS Accounts
75 lines • 2.34 kB
JavaScript
export const LogLevels = ['error', 'warn', 'info', 'debug', 'trace'];
const LEVELS = {
error: 0,
warn: 1,
info: 2,
debug: 3,
trace: 4
};
let CURRENT_LEVEL_NAME = 'warn';
let CURRENT_LEVEL = LEVELS[CURRENT_LEVEL_NAME];
export function setLogLevel(level) {
if (LEVELS[level] === undefined) {
throw new Error(`Invalid log level: ${level}`);
}
CURRENT_LEVEL_NAME = level;
CURRENT_LEVEL = LEVELS[level];
}
// helper to serialize non-object args into a single string
function serializeArgs(args) {
return args
.map((a) => typeof a === 'string' ? a : a instanceof Error ? a.stack || a.message : JSON.stringify(a))
.join(' ');
}
function isError(obj) {
return (obj instanceof Error ||
(typeof obj === 'object' && obj !== null && 'message' in obj && 'name' in obj));
}
// core log function: level check → prefix → JSON output
function logAt(level, args) {
if (LEVELS[level] > CURRENT_LEVEL)
return;
// Base log entry
const entry = {
timestamp: new Date().toISOString(),
level
};
// Separate object args and message args
const objectArgs = args.filter((a) => typeof a === 'object' && a !== null && !isError(a));
const messageArgs = args.filter((a) => typeof a !== 'object' || a === null);
const errorArgs = args.filter(isError);
// Merge all object arguments into the entry
for (const obj of objectArgs) {
Object.assign(entry, obj);
}
const msg = serializeArgs(messageArgs);
if (msg) {
entry.message = msg;
}
if (errorArgs.length > 0) {
entry.errors = errorArgs.map((e) => ({
name: e.name,
message: e.message,
stack: e.stack
}));
}
const line = JSON.stringify(entry);
switch (level) {
case 'error':
return console.error(line);
case 'warn':
return console.warn(line);
case 'info':
return console.info(line);
default:
return console.log(line);
}
}
export const log = {
error: (...args) => logAt('error', args),
warn: (...args) => logAt('warn', args),
info: (...args) => logAt('info', args),
debug: (...args) => logAt('debug', args),
trace: (...args) => logAt('trace', args)
};
//# sourceMappingURL=log.js.map