Skip to content

Commit 2e554ba

Browse files
committed
adicionado suporte de logs e tratamento de erros no hawk.so
1 parent 02ec5c8 commit 2e554ba

File tree

6 files changed

+101
-21
lines changed

6 files changed

+101
-21
lines changed

app/.env.sample

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ SELENIUM_HOST=localhost:4444
3434

3535
# Configurações de Debug
3636
DEBUG=true
37+
38+
# Configurações do Hawk.so
39+
HAWK_TOKEN=

app/composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
"vlucas/phpdotenv": "^5.6.1",
44
"aws/aws-sdk-php": "^3.0",
55
"php-curl-class/php-curl-class": "^11.0",
6-
"php-webdriver/webdriver": "^1.15"
6+
"php-webdriver/webdriver": "^1.15",
7+
"codex-team/hawk.php": "^2.2"
78
},
89
"autoload": {
910
"psr-4": {

app/config.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,18 @@
3131
define('CACHE_DIR', __DIR__ . '/cache');
3232
define('DEBUG', isset($_ENV['DEBUG']) ? filter_var($_ENV['DEBUG'], FILTER_VALIDATE_BOOLEAN) : false);
3333

34-
// Configurações de Redis
34+
/**
35+
* Configurações de Redis
36+
*/
3537
define('REDIS_HOST', isset($_ENV['REDIS_HOST']) ? $_ENV['REDIS_HOST'] : 'localhost');
3638
define('REDIS_PORT', isset($_ENV['REDIS_PORT']) ? $_ENV['REDIS_PORT'] : 6379);
3739
define('REDIS_PREFIX', isset($_ENV['REDIS_PREFIX']) ? $_ENV['REDIS_PREFIX'] : 'marreta:');
3840

41+
/**
42+
* Configurações do Hawk.so
43+
*/
44+
define('HAWK_TOKEN', isset($_ENV['HAWK_TOKEN']) ? $_ENV['HAWK_TOKEN'] : null);
45+
3946
/**
4047
* Configurações de Cache S3
4148
*/

app/inc/Logger.php

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
3+
namespace Inc;
4+
5+
use Exception;
6+
use \Hawk\Catcher;
7+
8+
class Logger
9+
{
10+
private static $instance = null;
11+
12+
private function __construct()
13+
{
14+
// Inicializa o Hawk apenas se houver um token configurado
15+
if (!empty(HAWK_TOKEN)) {
16+
Catcher::init([
17+
'integrationToken' => HAWK_TOKEN,
18+
]);
19+
}
20+
}
21+
22+
public static function getInstance(): Logger
23+
{
24+
if (self::$instance === null) {
25+
self::$instance = new self();
26+
}
27+
return self::$instance;
28+
}
29+
30+
/**
31+
* Registra um erro com contexto
32+
*
33+
* @param string $message Mensagem de erro
34+
* @param array $context Dados adicionais de contexto
35+
* @param string $type Tipo/categoria do erro
36+
*/
37+
public function error(string $message, array $context = [], string $type = 'WARNING'): void
38+
{
39+
// Se não houver token do Hawk configurado, não gera log
40+
if (empty(HAWK_TOKEN)) {
41+
return;
42+
}
43+
44+
// Registra no Hawk
45+
try {
46+
Catcher::get()->sendException(new Exception($message), [
47+
'type' => $type,
48+
'context' => $context
49+
]);
50+
} catch (Exception $e) {
51+
// Se o Hawk falhar, já temos o log em arquivo como backup
52+
error_log("Falha ao enviar erro para o Hawk: " . $e->getMessage());
53+
}
54+
}
55+
56+
/**
57+
* Registra um erro específico de URL
58+
*
59+
* @param string $url A URL que gerou o erro
60+
* @param string $error_group Grupo/categoria do erro
61+
* @param string $message_error Detalhes adicionais do erro
62+
* @param string $type Tipo/categoria do erro
63+
*/
64+
public function log(string $url, string $error_group, string $message_error = '', string $type = 'WARNING'): void
65+
{
66+
$this->error($error_group, [
67+
'url' => $url,
68+
'timestamp' => time(),
69+
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
70+
'message_error' => $message_error
71+
], $type);
72+
}
73+
}

app/inc/URLAnalyzer.php

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@
1515

1616
require_once 'Rules.php';
1717
require_once 'Cache.php';
18+
require_once 'Logger.php';
1819

1920
use Curl\Curl;
2021
use Facebook\WebDriver\Remote\DesiredCapabilities;
2122
use Facebook\WebDriver\Remote\RemoteWebDriver;
2223
use Facebook\WebDriver\Firefox\FirefoxOptions;
2324
use Facebook\WebDriver\Firefox\FirefoxProfile;
2425
use Facebook\WebDriver\Chrome\ChromeOptions;
26+
use Inc\Logger;
2527

2628
class URLAnalyzer
2729
{
@@ -88,19 +90,6 @@ public function checkRedirects($url)
8890
];
8991
}
9092

91-
/**
92-
* Registra erros no arquivo de log
93-
*
94-
* @param string $url URL que gerou o erro
95-
* @param string $error Mensagem de erro
96-
*/
97-
private function logError($url, $error)
98-
{
99-
$timestamp = date('Y-m-d H:i:s');
100-
$logEntry = "[{$timestamp}] URL: {$url} - Error: {$error}" . PHP_EOL;
101-
file_put_contents(__DIR__ . '/../logs/error.log', $logEntry, FILE_APPEND);
102-
}
103-
10493
/**
10594
* Método principal para análise de URLs
10695
*
@@ -126,8 +115,8 @@ public function analyze($url)
126115
$host = preg_replace('/^www\./', '', $host);
127116

128117
if (in_array($host, BLOCKED_DOMAINS)) {
129-
$error = 'Este domínio está bloqueado para extração.';
130-
$this->logError($cleanUrl, $error);
118+
$error = 'BLOCKED_DOMAINS';
119+
Logger::getInstance()->log($cleanUrl, $error);
131120
throw new Exception($error);
132121
}
133122

@@ -142,8 +131,9 @@ public function analyze($url)
142131
return $processedContent;
143132
}
144133
} catch (Exception $e) {
145-
$this->logError($cleanUrl, "Selenium fetch error: " . $e->getMessage());
146-
throw new Exception("Não foi possível obter o conteúdo via Selenium");
134+
$error = 'SELENIUM_ERROR';
135+
Logger::getInstance()->log($cleanUrl, 'SELENIUM_ERROR', $e->getMessage());
136+
throw new Exception($error);
147137
}
148138
}
149139

@@ -156,7 +146,7 @@ public function analyze($url)
156146
return $processedContent;
157147
}
158148
} catch (Exception $e) {
159-
$this->logError($cleanUrl, "Direct fetch error: " . $e->getMessage());
149+
Logger::getInstance()->log($cleanUrl, 'DIRECT_FETCH_ERROR', $e->getMessage());
160150
}
161151

162152
// 6. Tenta buscar do Wayback Machine como fallback
@@ -168,9 +158,10 @@ public function analyze($url)
168158
return $processedContent;
169159
}
170160
} catch (Exception $e) {
171-
$this->logError($cleanUrl, "Wayback Machine error: " . $e->getMessage());
161+
Logger::getInstance()->log($cleanUrl, 'WAYBACK_FETCH_ERROR', $e->getMessage());
172162
}
173163

164+
Logger::getInstance()->log($cleanUrl, 'GENERAL_FETCH_ERROR');
174165
throw new Exception("Não foi possível obter o conteúdo da URL");
175166
}
176167

docker-entrypoint.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ if [ -n "${SELENIUM_HOST}" ]; then
9090
echo "SELENIUM_HOST=${SELENIUM_HOST}" >> /app/.env
9191
fi
9292

93+
# Configurações do Hawk.so
94+
if [ -n "${HAWK_TOKEN}" ]; then
95+
echo "HAWK_TOKEN=${HAWK_TOKEN}" >> /app/.env
96+
fi
97+
9398
log_success "Variáveis de ambiente configuradas"
9499

95100
# === Ajuste de Permissões ===

0 commit comments

Comments
 (0)