Skip to content

Commit 4cd475c

Browse files
committed
removido o hawk, implementado monolog
1 parent 4855f4e commit 4cd475c

File tree

8 files changed

+130
-63
lines changed

8 files changed

+130
-63
lines changed

README.en.md

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ SITE_NAME="Marreta"
8787
SITE_DESCRIPTION="Paywall hammer!"
8888
SITE_URL=http://localhost
8989
DNS_SERVERS=1.1.1.1,8.8.8.8
90-
DEBUG=true
90+
LOG_LEVEL=WARNING
9191
SELENIUM_HOST=selenium-hub:4444
9292
LANGUAGE=pt-br
9393
```
@@ -99,8 +99,6 @@ docker-compose up -d
9999

100100
Done! It will be running at `http://localhost` 🎉
101101

102-
The `DEBUG` option when `true` will not generate cache!
103-
104102
## ⚙️ Customization
105103

106104
The configurations are organized in `data/`:
@@ -194,23 +192,32 @@ Important settings:
194192

195193
After setting up Selenium, make sure to set the `SELENIUM_HOST` variable in your environment to point to the Selenium hub (typically `selenium-hub:4444`).
196194

197-
### Error monitoring
195+
### Logging System
196+
197+
Logs are stored in `app/logs/app.log` with automatic 7-day rotation.
198198

199-
Marreta uses [Hawk.so](https://hawk.so), an open-source error monitoring platform. To configure monitoring, add the following variables to your `.env` or docker:
199+
Log settings available in `.env` or docker:
200200

201201
```env
202-
HAWK_TOKEN=your_token
202+
LOG_LEVEL=WARNING
203203
```
204204

205-
You can host your own Hawk.so instance or use the hosted service at [hawk.so](https://hawk.so). The source code is available at [github.com/codex-team/hawk](https://github.com/codex-team/hawk).
205+
Available log levels:
206+
- DEBUG: Detailed information for debugging
207+
- INFO: General operational information
208+
- WARNING: Warnings that deserve attention (default)
209+
- ERROR: Errors that don't stop operation
210+
- CRITICAL: Critical errors that need immediate attention
206211

207212
## 🛠️ Maintenance
208213

209214
### Logs
210215

211-
See what's happening:
216+
View application logs:
212217
```bash
213218
docker-compose logs app
219+
# or directly from the log file
220+
cat app/logs/app.log
214221
```
215222

216223
### Clearing the cache

README.md

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ SITE_NAME="Marreta"
8787
SITE_DESCRIPTION="Chapéu de paywall é marreta!"
8888
SITE_URL=http://localhost
8989
DNS_SERVERS=1.1.1.1,8.8.8.8
90-
DEBUG=true
90+
LOG_LEVEL=WARNING
9191
SELENIUM_HOST=selenium-hub:4444
9292
LANGUAGE=pt-br
9393
```
@@ -99,8 +99,6 @@ docker-compose up -d
9999

100100
Pronto! Vai estar rodando em `http://localhost` 🎉
101101

102-
A opção de `DEBUG` quando `true` não irá gerar cache!
103-
104102
## ⚙️ Personalizando
105103

106104
As configurações estão organizadas em `data/`:
@@ -194,23 +192,32 @@ Configurações importantes:
194192

195193
Após configurar o Selenium, certifique-se de definir a variável `SELENIUM_HOST` no seu ambiente para apontar para o hub do Selenium (geralmente `selenium-hub:4444`).
196194

197-
### Monitoramento de erros
195+
### Sistema de Logs
196+
197+
Os logs são armazenados em `app/logs/app.log` com rotação automática a cada 7 dias.
198198

199-
O Marreta utiliza o [Hawk.so](https://hawk.so), uma plataforma de código aberto para monitoramento de erros. Para configurar o monitoramento, adicione as seguintes variáveis ao seu `.env` ou docker:
199+
Configurações de log disponíveis no `.env` ou docker:
200200

201201
```env
202-
HAWK_TOKEN=seu_token
202+
LOG_LEVEL=WARNING
203203
```
204204

205-
Você pode hospedar sua própria instância do Hawk.so ou usar o serviço hospedado em [hawk.so](https://hawk.so). O código fonte está disponível em [github.com/codex-team/hawk](https://github.com/codex-team/hawk).
205+
Níveis de log disponíveis:
206+
- DEBUG: Informações detalhadas para debug
207+
- INFO: Informações gerais sobre operações
208+
- WARNING: Avisos que merecem atenção (padrão)
209+
- ERROR: Erros que não interrompem a operação
210+
- CRITICAL: Erros críticos que precisam de atenção imediata
206211

207212
## 🛠️ Manutenção
208213

209214
### Logs
210215

211-
Ver o que tá acontecendo:
216+
Ver os logs da aplicação:
212217
```bash
213218
docker-compose logs app
219+
# ou diretamente do arquivo de log
220+
cat app/logs/app.log
214221
```
215222

216223
### Limpando o cache

app/composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"aws/aws-sdk-php": "^3.0",
55
"php-curl-class/php-curl-class": "^11.0",
66
"php-webdriver/webdriver": "^1.15",
7-
"codex-team/hawk.php": "^2.2"
7+
"monolog/monolog": "^3.8.1"
88
},
99
"autoload": {
1010
"psr-4": {

app/config.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,6 @@
5252
filter_var($_ENV['DISABLE_CACHE'], FILTER_VALIDATE_BOOLEAN) : false);
5353
define('SELENIUM_HOST', $_ENV['SELENIUM_HOST'] ?? 'localhost:4444');
5454
define('CACHE_DIR', __DIR__ . '/cache');
55-
define('DEBUG', isset($_ENV['DEBUG']) ?
56-
filter_var($_ENV['DEBUG'], FILTER_VALIDATE_BOOLEAN) : false);
5755
define('LANGUAGE', $_ENV['LANGUAGE'] ?? 'pt-br');
5856

5957
/**
@@ -65,10 +63,11 @@
6563
define('REDIS_PREFIX', $_ENV['REDIS_PREFIX'] ?? 'marreta:');
6664

6765
/**
68-
* Hawk.so settings
69-
* Configurações do Hawk.so
66+
* Logging settings
67+
* Configurações de log
7068
*/
71-
define('HAWK_TOKEN', $_ENV['HAWK_TOKEN'] ?? null);
69+
define('LOG_LEVEL', $_ENV['LOG_LEVEL'] ?? 'WARNING'); // Available: DEBUG, INFO, WARNING, ERROR, CRITICAL
70+
define('LOG_DAYS_TO_KEEP', 7);
7271

7372
/**
7473
* S3 Cache settings

app/inc/Logger.php

Lines changed: 88 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,21 @@
22

33
namespace Inc;
44

5+
use Monolog\Logger as MonologLogger;
6+
use Monolog\Handler\RotatingFileHandler;
7+
use Monolog\Handler\StreamHandler;
8+
use Monolog\Formatter\LineFormatter;
9+
use Monolog\Level;
510
use Exception;
6-
use \Hawk\Catcher;
711

812
/**
913
* Error logging and monitoring class
1014
* Classe de monitoramento e registro de erros
1115
*
12-
* This class implements error logging functionality using Hawk.so
16+
* This class implements error logging functionality using Monolog
1317
* for monitoring and tracking application errors.
1418
*
15-
* Esta classe implementa funcionalidades de registro de erros usando Hawk.so
19+
* Esta classe implementa funcionalidades de registro de erros usando Monolog
1620
* para monitoramento e rastreamento de erros da aplicação.
1721
*/
1822
class Logger
@@ -23,20 +27,59 @@ class Logger
2327
*/
2428
private static $instance = null;
2529

30+
/**
31+
* @var MonologLogger Monolog logger instance
32+
* @var MonologLogger Instância do logger Monolog
33+
*/
34+
private $logger;
35+
36+
/**
37+
* @var array Log level mapping
38+
* @var array Mapeamento de níveis de log
39+
*/
40+
private $logLevels = [
41+
'DEBUG' => \Monolog\Level::Debug,
42+
'INFO' => \Monolog\Level::Info,
43+
'WARNING' => \Monolog\Level::Warning,
44+
'ERROR' => \Monolog\Level::Error,
45+
'CRITICAL' => \Monolog\Level::Critical
46+
];
47+
2648
/**
2749
* Private constructor to prevent direct instantiation
2850
* Construtor privado para prevenir instanciação direta
2951
*
30-
* Initializes Hawk monitoring
31-
* Inicializa o monitoramento Hawk
52+
* Initializes Monolog logger with file rotation
53+
* Inicializa o logger Monolog com rotação de arquivos
3254
*/
3355
private function __construct()
3456
{
35-
// Initialize Hawk
36-
// Inicializa o Hawk
37-
Catcher::init([
38-
'integrationToken' => HAWK_TOKEN,
39-
]);
57+
$this->logger = new MonologLogger('marreta');
58+
59+
// Setup rotating file handler with 7 days retention
60+
// Configura manipulador de arquivo rotativo com retenção de 7 dias
61+
$handler = new RotatingFileHandler(
62+
__DIR__ . '/../logs/app.log',
63+
LOG_DAYS_TO_KEEP,
64+
$this->getLogLevel()
65+
);
66+
67+
// Custom line format
68+
// Formato de linha personalizado
69+
$dateFormat = "Y-m-d H:i:s";
70+
$output = "[%datetime%] %level_name%: %message% %context% %extra%\n";
71+
$formatter = new LineFormatter($output, $dateFormat);
72+
$handler->setFormatter($formatter);
73+
74+
$this->logger->pushHandler($handler);
75+
76+
// If LOG_LEVEL is DEBUG, also log to stderr
77+
// Se LOG_LEVEL for DEBUG, também loga no stderr
78+
if (defined('LOG_LEVEL') && LOG_LEVEL === 'DEBUG') {
79+
$streamHandler = new StreamHandler('php://stderr', \Monolog\Level::Debug);
80+
$streamHandler->setFormatter($formatter);
81+
$this->logger->pushHandler($streamHandler);
82+
}
4083
}
4184

4285
/**
@@ -53,28 +96,42 @@ public static function getInstance(): Logger
5396
return self::$instance;
5497
}
5598

99+
/**
100+
* Gets configured log level from environment or default
101+
* Obtém nível de log configurado do ambiente ou padrão
102+
*
103+
* @return Level Monolog log level / Nível de log do Monolog
104+
*/
105+
private function getLogLevel(): Level
106+
{
107+
$configLevel = defined('LOG_LEVEL') ? LOG_LEVEL : 'WARNING';
108+
return $this->logLevels[$configLevel] ?? Level::Warning;
109+
}
110+
111+
/**
112+
* Logs a message with context at specified level
113+
* Registra uma mensagem com contexto no nível especificado
114+
*
115+
* @param string $message Log message / Mensagem de log
116+
* @param array $context Additional context data / Dados adicionais de contexto
117+
* @param string $level Log level / Nível de log
118+
*/
119+
public function log(string $message, array $context = [], string $level = 'WARNING'): void
120+
{
121+
$logLevel = $this->logLevels[$level] ?? \Monolog\Level::Warning;
122+
$this->logger->log($logLevel, $message, $context);
123+
}
124+
56125
/**
57126
* Logs an error with context
58127
* Registra um erro com contexto
59128
*
60129
* @param string $message Error message / Mensagem de erro
61130
* @param array $context Additional context data / Dados adicionais de contexto
62-
* @param string $type Error type/category / Tipo/categoria do erro
63131
*/
64-
public function error(string $message, array $context = [], string $type = 'WARNING'): void
132+
public function error(string $message, array $context = []): void
65133
{
66-
// Log to Hawk
67-
// Registra no Hawk
68-
try {
69-
Catcher::get()->sendException(new Exception($message), [
70-
'type' => $type,
71-
'context' => $context
72-
]);
73-
} catch (Exception $e) {
74-
// If Hawk fails, we already have file logging as backup
75-
// Se o Hawk falhar, já temos o log em arquivo como backup
76-
error_log("Failed to send error to Hawk / Falha ao enviar erro para o Hawk: " . $e->getMessage());
77-
}
134+
$this->log($message, $context, 'ERROR');
78135
}
79136

80137
/**
@@ -84,21 +141,17 @@ public function error(string $message, array $context = [], string $type = 'WARN
84141
* @param string $url The URL that generated the error / A URL que gerou o erro
85142
* @param string $error_group Error group/category / Grupo/categoria do erro
86143
* @param string $message_error Additional error details / Detalhes adicionais do erro
87-
* @param string $type Error type/category / Tipo/categoria do erro
144+
* @param string $level Log level / Nível de log
88145
*/
89-
public function log(string $url, string $error_group, string $message_error = '', string $type = 'WARNING'): void
146+
public function logUrl(string $url, string $error_group, string $message_error = '', string $level = 'WARNING'): void
90147
{
91-
// If no Hawk token is configured, don't generate log
92-
// Se não houver token do Hawk configurado, não gera log
93-
if (empty(HAWK_TOKEN)) {
94-
return;
95-
}
96-
97-
$this->error($error_group, [
148+
$context = [
98149
'url' => $url,
99150
'timestamp' => time(),
100151
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
101152
'message_error' => $message_error
102-
], $type);
153+
];
154+
155+
$this->log($error_group, $context, $level);
103156
}
104-
}
157+
}

app/inc/URLAnalyzer.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -814,8 +814,8 @@ private function addBrandBar($dom, $xpath)
814814
$brandDiv->appendChild($brandHtml);
815815
$body->appendChild($brandDiv);
816816

817-
// Add debug panel if DEBUG is true / Adicionar painel de depuração se DEBUG for verdadeiro
818-
if (DEBUG) {
817+
// Add debug panel if LOG_LEVEL is DEBUG / Adicionar painel de depuração se LOG_LEVEL for DEBUG
818+
if (LOG_LEVEL === 'DEBUG') {
819819
$debugDiv = $dom->createElement('div');
820820
$debugDiv->setAttribute('style', 'z-index: 99999; position: fixed; bottom: 10px; right: 10px; background: rgba(0,0,0,0.8); color: #fff; font-size: 13px; line-height: 1.4; padding: 10px; border-radius: 3px; font-family: monospace; max-height: 200px; overflow-y: auto;');
821821

default.conf

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ server {
4343

4444
# Block access to sensitive directories
4545
# Bloqueia acesso a diretórios sensíveis
46-
location ~ ^/(logs|cache|inc|data|cli)/ {
47-
return 301 /;
46+
location ~ ^/(logs|cache|inc|data|cli|bin|languages|vendor)/ {
47+
deny all;
48+
return 403;
4849
}
4950

5051
location / {

docker-compose.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ services:
1313
- SITE_URL=${SITE_URL:-https://marreta.localhost}
1414
- DNS_SERVERS=${DNS_SERVER:-}
1515
- LANGUAGE=${LANGUAGE:-}
16-
- DEBUG=${DEBUG:-}
16+
- LOG_LEVEL=${LOG_LEVEL:-WARNING}
1717
- SELENIUM_HOST=${SELENIUM_HOST:-selenium-hub:4444}
1818
restart: unless-stopped
1919
selenium-chromium:
@@ -57,4 +57,4 @@ services:
5757
ports:
5858
- 4442:4442
5959
- 4443:4443
60-
- 4444:4444
60+
- 4444:4444

0 commit comments

Comments
 (0)