api-stats-logger
Version:
SDK completo de logging e monitoramento de APIs com nova estrutura de logs organizada, auto-instrumentação, dashboard em tempo real e CLI para configuração automática. Suporta logs estruturados por contexto (HTTP, business, security, system) com campos op
113 lines (93 loc) • 3.49 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 (desabilitado por segurança)
_setupPerformanceMetrics() {
// Coleta de métricas do sistema desabilitada por motivos de segurança
// As métricas detalhadas podem expor informações sensíveis sobre o servidor
console.log('📊 Métricas de sistema desabilitadas por segurança');
}
// Middleware para Express
static expressMiddleware(options = {}) {
return middleware.express(options);
}
// Middleware para NestJS
static nestMiddleware(options = {}) {
return middleware.nest(options);
}
// Middleware para Fastify
static fastifyMiddleware(options = {}) {
return middleware.fastify(options);
}
// Middleware para Koa
static koaMiddleware(options = {}) {
return middleware.koa(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;