traceperf
Version:
High-performance function execution tracking and monitoring for Node.js
96 lines • 3.17 kB
JavaScript
import { LEVEL_COLORS, LEVEL_ICONS } from '../core/constants';
import { colorize, dim, supportsColor } from '../utils/colors';
/**
* CLI formatter for console output
* Formats log entries with colors, icons, and indentation
*/
export class CliFormatter {
/**
* Create a new CliFormatter instance
*
* @param options - Formatter options
*/
constructor(options = {}) {
var _a, _b;
this._colorEnabled = (_a = options.colorEnabled) !== null && _a !== void 0 ? _a : supportsColor();
this._indentSize = (_b = options.indentSize) !== null && _b !== void 0 ? _b : 2;
}
/**
* Format a log entry for CLI output
*
* @param level - The log level
* @param message - The log message
* @param args - Additional arguments
* @param meta - Metadata for the log entry
* @returns The formatted log entry
*/
format(level, message, args, meta) {
const timestamp = this.formatTimestamp(meta.timestamp);
const levelStr = this.formatLevel(level);
const indent = ' '.repeat(meta.indentLevel * this._indentSize);
const formattedMessage = this.formatMessage(message, args);
return `${timestamp} ${levelStr} ${indent}${formattedMessage}`;
}
/**
* Format a timestamp
*
* @param date - The date to format
* @returns The formatted timestamp
*/
formatTimestamp(date) {
const timeStr = date.toISOString().replace(/T/, ' ').replace(/\..+/, '');
return this._colorEnabled ? dim(`[${timeStr}]`) : `[${timeStr}]`;
}
/**
* Format a log level
*
* @param level - The log level
* @returns The formatted log level
*/
formatLevel(level) {
const icon = LEVEL_ICONS[level];
const text = level.toUpperCase();
if (this._colorEnabled) {
return colorize(`${icon} ${text}`, LEVEL_COLORS[level]);
}
return `${icon} ${text}`;
}
/**
* Format a message and its arguments
*
* @param message - The message to format
* @param args - Additional arguments
* @returns The formatted message
*/
formatMessage(message, args) {
let formattedMessage;
if (typeof message === 'string') {
formattedMessage = message;
}
else {
try {
formattedMessage = JSON.stringify(message, null, 2);
}
catch (error) {
formattedMessage = String(message);
}
}
// Format additional arguments
if (args.length > 0) {
const formattedArgs = args.map(arg => {
if (typeof arg === 'object' && arg !== null) {
try {
return JSON.stringify(arg, null, 2);
}
catch (error) {
return String(arg);
}
}
return String(arg);
}).join(' ');
formattedMessage = `${formattedMessage} ${formattedArgs}`;
}
return formattedMessage;
}
}
//# sourceMappingURL=cli.js.map