logPath = __DIR__ . '/../../storage/logs/'; // Desativar temporariamente o DatabaseManager para evitar loops // $this->db = DatabaseManager::getInstance(); // Criar diretório se não existir if (!is_dir($this->logPath)) { mkdir($this->logPath, 0755, true); } } /** * Log inteligente - escreve em ficheiros pequenos e move para error_logs */ public function log(string $level, string $message, array $context = []): void { // Desativar temporariamente o logging para evitar crescimento de ficheiros // $date = date('Y-m-d'); // $filename = "{$this->logPath}{$level}-{$date}.log"; // // Verificar se ficheiro está muito grande OU se é de um dia anterior // $shouldProcess = false; // $reason = ''; // if (file_exists($filename)) { // $fileSize = filesize($filename); // $fileAge = time() - filemtime($filename); // if ($fileSize > self::MAX_FILE_SIZE) { // $shouldProcess = true; // $reason = 'size_limit'; // } elseif ($fileAge > 3600) { // 1 hora // $shouldProcess = true; // $reason = 'age_limit'; // } // } // if ($shouldProcess) { // // NÃO processar automaticamente - será feito via API separada // // Apenas apagar ficheiro se for muito antigo (> 24h) // if (($fileAge ?? 0) > 24 * 3600) { // unlink($filename); // // Log do processamento automático // $this->log('info', "Ficheiro antigo removido: {$filename}", [ // 'reason' => $reason, // 'file_size' => $this->formatBytes($fileSize ?? 0), // 'file_age_hours' => round(($fileAge ?? 0) / 3600, 1), // 'level' => $level // ]); // } // } // // Escrever nova entrada // $logEntry = [ // 'timestamp' => date('Y-m-d H:i:s'), // 'level' => $level, // 'message' => $message, // 'context' => $context // ]; // $line = json_encode($logEntry) . PHP_EOL; // file_put_contents($filename, $line, FILE_APPEND | LOCK_EX); // Log simples para evitar crescimento de ficheiros error_log("Logger[{$level}]: {$message}"); } /** * Processar ficheiro para tabela error_logs (estrutura rica) */ public function processFileToErrorLogs(string $filename, string $level): int { if (!file_exists($filename)) { return 0; } try { $this->createErrorLogsTable(); $handle = fopen($filename, 'r'); if (!$handle) { return 0; } $linesProcessed = 0; $batch = []; $batchSize = 50; while (($line = fgets($handle)) !== false) { $data = json_decode(trim($line), true); if ($data) { $errorData = $this->formatLogEntryForErrorLogs($data, $level); $batch[] = $errorData; if (count($batch) >= $batchSize) { $this->insertErrorLogsBatch($batch); $linesProcessed += count($batch); $batch = []; } } } // Inserir batch final if (!empty($batch)) { $this->insertErrorLogsBatch($batch); $linesProcessed += count($batch); } fclose($handle); // Apagar ficheiro após processamento bem-sucedido if ($linesProcessed > 0 && file_exists($filename)) { unlink($filename); } return $linesProcessed; } catch (\Exception $e) { ErrorReporter::report($e, [ 'context' => 'logger_process_file_to_error_logs', 'filename' => $filename, 'level' => $level ]); return 0; } } /** * Formatar entrada de log para estrutura error_logs */ private function formatLogEntryForErrorLogs(array $data, string $level): array { $context = $data['context'] ?? []; return [ 'unique_id' => $this->generateUniqueId(), 'project_name' => $context['project_name'] ?? 'CRM', 'environment' => $context['environment'] ?? 'production', 'error_type' => $context['error_type'] ?? 'LogEntry', 'severity' => $this->mapLevelToSeverity($level), 'message' => substr($data['message'] ?? '', 0, 1000), 'file_path' => $context['file_path'] ?? '', 'line_number' => $context['line_number'] ?? 0, 'stack_trace' => $context['stack_trace'] ?? '', 'context_data' => json_encode($context), 'user_id' => $context['user_id'] ?? '', 'session_id' => $context['session_id'] ?? '', 'request_id' => $context['request_id'] ?? '', 'ip_address' => $context['ip_address'] ?? '', 'user_agent' => $context['user_agent'] ?? '', 'url' => $context['url'] ?? '', 'http_method' => $context['http_method'] ?? '', 'request_data' => json_encode($context['request_data'] ?? []), 'server_data' => json_encode($context['server_data'] ?? []), 'occurrences' => 1, 'first_seen' => $data['timestamp'] ?? date('Y-m-d H:i:s'), 'last_seen' => $data['timestamp'] ?? date('Y-m-d H:i:s'), 'status' => 'open', 'assigned_to' => '', 'resolution_notes' => '', 'resolved_at' => null, 'created_at' => $data['timestamp'] ?? date('Y-m-d H:i:s'), 'updated_at' => $data['timestamp'] ?? date('Y-m-d H:i:s') ]; } /** * Mapear nível de log para severidade */ private function mapLevelToSeverity(string $level): string { switch (strtolower($level)) { case 'critical': case 'emergency': return 'critical'; case 'error': return 'error'; case 'warning': return 'warning'; case 'info': return 'info'; case 'debug': return 'debug'; default: return 'info'; } } /** * Gerar ID único */ private function generateUniqueId(): string { return strtoupper(substr(md5(uniqid() . microtime()), 0, 25)); } /** * Inserir batch de logs na tabela error_logs */ private function insertErrorLogsBatch(array $batch): void { if (empty($batch)) return; $values = []; $params = []; foreach ($batch as $log) { $values[] = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; $params = array_merge($params, [ $log['unique_id'], $log['project_name'], $log['environment'], $log['error_type'], $log['severity'], $log['message'], $log['file_path'], $log['line_number'], $log['stack_trace'], $log['context_data'], $log['user_id'], $log['session_id'], $log['request_id'], $log['ip_address'], $log['user_agent'], $log['url'], $log['http_method'], $log['request_data'], $log['server_data'], $log['occurrences'], $log['first_seen'], $log['last_seen'], $log['status'], $log['assigned_to'], $log['resolution_notes'], $log['resolved_at'], $log['created_at'], $log['updated_at'] ]); } $sql = "INSERT INTO error_logs ( unique_id, project_name, environment, error_type, severity, message, file_path, line_number, stack_trace, context_data, user_id, session_id, request_id, ip_address, user_agent, url, http_method, request_data, server_data, occurrences, first_seen, last_seen, status, assigned_to, resolution_notes, resolved_at, created_at, updated_at ) VALUES " . implode(', ', $values); $this->db->query($sql, $params); } /** * Criar tabela error_logs se não existir */ private function createErrorLogsTable(): void { $sql = "CREATE TABLE IF NOT EXISTS error_logs ( id INT AUTO_INCREMENT PRIMARY KEY, unique_id VARCHAR(25) NOT NULL UNIQUE, project_name VARCHAR(100) NOT NULL DEFAULT 'CRM', environment VARCHAR(50) NOT NULL DEFAULT 'production', error_type VARCHAR(100) NOT NULL DEFAULT 'LogEntry', severity ENUM('debug', 'info', 'warning', 'error', 'critical') NOT NULL DEFAULT 'info', message TEXT NOT NULL, file_path VARCHAR(500), line_number INT, stack_trace TEXT, context_data JSON, user_id VARCHAR(50), session_id VARCHAR(100), request_id VARCHAR(50), ip_address VARCHAR(45), user_agent TEXT, url VARCHAR(500), http_method VARCHAR(10), request_data JSON, server_data JSON, occurrences INT NOT NULL DEFAULT 1, first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, status ENUM('open', 'resolved', 'ignored') NOT NULL DEFAULT 'open', assigned_to VARCHAR(100), resolution_notes TEXT, resolved_at TIMESTAMP NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_severity (severity), INDEX idx_status (status), INDEX idx_project (project_name), INDEX idx_environment (environment), INDEX idx_created_at (created_at), INDEX idx_unique_id (unique_id) )"; $this->db->query($sql); } /** * Obter estatísticas dos logs */ public function getStats(): array { try { // Estatísticas dos ficheiros $files = glob($this->logPath . '*.log'); $totalFiles = count($files); $totalSize = 0; foreach ($files as $file) { if (file_exists($file)) { $totalSize += filesize($file); } } // Estatísticas da base de dados (error_logs) $totalLogsInDb = 0; $levels = []; try { $sql = "SELECT COUNT(*) as total, severity, COUNT(CASE WHEN status = 'open' THEN 1 END) as open_count, COUNT(CASE WHEN status = 'resolved' THEN 1 END) as resolved_count FROM error_logs GROUP BY severity"; $results = $this->db->fetchAll($sql); foreach ($results as $row) { $totalLogsInDb += $row['total']; $levels[$row['severity']] = [ 'total' => $row['total'], 'open' => $row['open_count'], 'resolved' => $row['resolved_count'] ]; } // Se não há resultados, tentar contar total if ($totalLogsInDb === 0) { $countResult = $this->db->fetch("SELECT COUNT(*) as total FROM error_logs"); $totalLogsInDb = $countResult['total'] ?? 0; } } catch (\Exception $e) { // Tabela pode não existir ainda $totalLogsInDb = 0; } // Logs recentes (limitados para performance) $recentEntries = []; try { $sql = "SELECT severity, message, created_at FROM error_logs ORDER BY created_at DESC LIMIT 5"; $recentResults = $this->db->fetchAll($sql); foreach ($recentResults as $row) { $recentEntries[] = "[{$row['severity']}] " . substr($row['message'], 0, 100); } } catch (\Exception $e) { // Ignorar se tabela não existir } return [ 'total_files' => $totalFiles, 'total_size' => $totalSize, 'total_size_formatted' => $this->formatBytes($totalSize), 'total_logs_in_db' => $totalLogsInDb, 'levels' => $levels, 'recent_entries' => $recentEntries, 'status' => 'unified_system' ]; } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'logger_get_stats']); return [ 'total_files' => 0, 'total_size' => 0, 'total_size_formatted' => '0 B', 'total_logs_in_db' => 0, 'levels' => [], 'recent_entries' => [], 'status' => 'error' ]; } } /** * Limpeza automática (apenas ficheiros antigos) */ public function cleanup(int $daysToKeep = 7): int { $files = glob($this->logPath . '*.log'); $deletedCount = 0; $maxAge = $daysToKeep * 24 * 60 * 60; foreach ($files as $file) { if (file_exists($file) && (time() - filemtime($file)) > $maxAge) { // NÃO processar automaticamente - será feito via API separada // Apenas apagar ficheiro antigo unlink($file); $deletedCount++; } } return $deletedCount; } /** * Processamento inteligente - só processa se necessário * Retorna estatísticas do que foi processado */ public function processIfNeeded(): array { $files = glob($this->logPath . '*.log'); $processed = false; $filesProcessed = 0; $filesSkipped = 0; $totalLinesProcessed = 0; $reason = 'no_files_to_process'; if (empty($files)) { return [ 'processed' => false, 'files_processed' => 0, 'files_skipped' => 0, 'total_lines_processed' => 0, 'reason' => 'no_files_found' ]; } foreach ($files as $file) { if (!file_exists($file)) continue; $fileSize = filesize($file); $fileAge = time() - filemtime($file); $maxAge = 30 * 60; // 30 minutos (mais agressivo) // Processar se: ficheiro > 1MB OU ficheiro > 30min OU ficheiro > 100KB $shouldProcess = false; $processReason = ''; if ($fileSize > self::MAX_FILE_SIZE) { $shouldProcess = true; $processReason = 'size_large'; } elseif ($fileAge > $maxAge) { $shouldProcess = true; $processReason = 'age_old'; } elseif ($fileSize > 100 * 1024) { // 100KB $shouldProcess = true; $processReason = 'size_medium'; } if ($shouldProcess) { // NÃO processar automaticamente - será feito via API separada // Apenas marcar como processado se ficheiro for muito antigo if ($fileAge > 24 * 3600) { // 24 horas unlink($file); $filesProcessed++; $processed = true; // Log do processamento $this->log('info', "Ficheiro antigo removido: {$file}", [ 'file_size' => $this->formatBytes($fileSize), 'file_age_minutes' => round($fileAge / 60, 1), 'level' => $this->extractLevelFromFilename($file), 'reason' => $processReason ]); } else { $filesSkipped++; } } else { $filesSkipped++; } } return [ 'processed' => $processed, 'files_processed' => $filesProcessed, 'files_skipped' => $filesSkipped, 'total_lines_processed' => $totalLinesProcessed, 'reason' => $processed ? 'files_processed' : 'no_files_need_processing' ]; } /** * Processar todos os ficheiros grandes */ public function processAllLargeFiles(): array { $files = glob($this->logPath . '*.log'); $filesProcessed = 0; $totalLinesProcessed = 0; $errors = []; foreach ($files as $file) { if (!file_exists($file)) continue; $fileSize = filesize($file); // NÃO processar automaticamente - será feito via API separada // Apenas marcar ficheiro grande para processamento posterior if ($fileSize > self::MAX_FILE_SIZE) { $filesProcessed++; // Log do ficheiro grande encontrado $this->log('info', "Ficheiro grande encontrado (não processado): {$file}", [ 'file_size' => $this->formatBytes($fileSize), 'level' => $this->extractLevelFromFilename($file) ]); } } return [ 'files_processed' => $filesProcessed, 'total_lines_processed' => $totalLinesProcessed, 'errors' => $errors ]; } /** * Extrair nível de log do nome do ficheiro */ private function extractLevelFromFilename(string $filename): string { $basename = basename($filename); $parts = explode('-', $basename); return $parts[0] ?? 'info'; } /** * Formatar bytes para legibilidade */ private function formatBytes(int $bytes): string { $units = ['B', 'KB', 'MB', 'GB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, 2) . ' ' . $units[$pow]; } // Métodos de conveniência public function emergency(string $message, array $context = []): void { $this->log('emergency', $message, $context); } public function alert(string $message, array $context = []): void { $this->log('alert', $message, $context); } public function critical(string $message, array $context = []): void { $this->log('critical', $message, $context); } public function error(string $message, array $context = []): void { $this->log('error', $message, $context); } public function warning(string $message, array $context = []): void { $this->log('warning', $message, $context); } public function notice(string $message, array $context = []): void { $this->log('notice', $message, $context); } public function info(string $message, array $context = []): void { $this->log('info', $message, $context); } public function debug(string $message, array $context = []): void { $this->log('debug', $message, $context); } }