@erickzao/api-stats-cli
Version:
CLI oficial para configuração automática do API Stats Logger
124 lines (105 loc) • 3.8 kB
JavaScript
const Logger = require('./logger');
const middleware = require('./middleware');
const autoInstrument = require('./auto-instrument');
class ApiStatsLogger extends Logger {
constructor(options = {}) {
// Configuração automática via environment variables
const config = {
apiKey: options.apiKey || process.env.API_STATS_API_KEY,
url: options.url || process.env.API_STATS_URL || 'http://localhost:3000/logs',
service: options.service || process.env.API_STATS_SERVICE || 'unknown-service',
environment: options.environment || process.env.API_STATS_ENVIRONMENT || process.env.NODE_ENV || 'development',
batchSize: parseInt(options.batchSize || process.env.API_STATS_BATCH_SIZE || '10'),
flushInterval: parseInt(options.flushInterval || process.env.API_STATS_FLUSH_INTERVAL || '2000'),
enabled: (options.enabled !== undefined) ? options.enabled : (process.env.API_STATS_ENABLED !== 'false'),
captureErrors: options.captureErrors !== false,
capturePerformance: options.capturePerformance !== false,
...options
};
if (!config.apiKey) {
throw new Error('API_STATS_API_KEY é obrigatório. Configure via options.apiKey ou variável de ambiente.');
}
super(config);
// Auto-instrumentação de erros não tratados
if (config.captureErrors) {
this._setupErrorCapture();
}
// Captura de métricas de performance
if (config.capturePerformance) {
this._setupPerformanceMetrics();
}
}
// Métodos de conveniência
info(message, metadata = {}) {
this.log({ level: 'info', message, metadata });
}
error(message, metadata = {}) {
this.log({ level: 'error', message, metadata });
}
warn(message, metadata = {}) {
this.log({ level: 'warn', message, metadata });
}
debug(message, metadata = {}) {
this.log({ level: 'debug', message, metadata });
}
// Instrumentação automática de erros
_setupErrorCapture() {
process.on('uncaughtException', (error) => {
this.error('Uncaught Exception', {
error: error.message,
stack: error.stack,
type: 'uncaughtException'
});
});
process.on('unhandledRejection', (reason, promise) => {
this.error('Unhandled Promise Rejection', {
reason: reason?.toString(),
stack: reason?.stack,
type: 'unhandledRejection'
});
});
}
// Métricas de performance do sistema
_setupPerformanceMetrics() {
if (typeof process !== 'undefined' && process.memoryUsage) {
setInterval(() => {
const memory = process.memoryUsage();
const cpuUsage = process.cpuUsage();
this.log({
level: 'info',
message: 'System metrics',
metadata: {
type: 'system_metrics',
memory: {
rss: Math.round(memory.rss / 1024 / 1024), // MB
heapUsed: Math.round(memory.heapUsed / 1024 / 1024), // MB
heapTotal: Math.round(memory.heapTotal / 1024 / 1024) // MB
},
cpu: {
user: cpuUsage.user,
system: cpuUsage.system
},
uptime: Math.round(process.uptime())
}
});
}, 60000); // A cada minuto
}
}
// Middleware para Express
static expressMiddleware(options = {}) {
return middleware.express(options);
}
// Middleware para NestJS
static nestMiddleware(options = {}) {
return middleware.nest(options);
}
// Inicialização automática com detecção de framework
static init(options = {}) {
const logger = new ApiStatsLogger(options);
if (options.autoDetect !== false) {
autoInstrument.setup(logger, options);
}
return logger;
}
}
module.exports = ApiStatsLogger;