Skip to content

Commit

Permalink
removido o hawk, implementado monolog
Browse files Browse the repository at this point in the history
  • Loading branch information
altendorfme committed Jan 24, 2025
1 parent 4855f4e commit 4cd475c
Show file tree
Hide file tree
Showing 8 changed files with 130 additions and 63 deletions.
23 changes: 15 additions & 8 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ SITE_NAME="Marreta"
SITE_DESCRIPTION="Paywall hammer!"
SITE_URL=http://localhost
DNS_SERVERS=1.1.1.1,8.8.8.8
DEBUG=true
LOG_LEVEL=WARNING
SELENIUM_HOST=selenium-hub:4444
LANGUAGE=pt-br
```
Expand All @@ -99,8 +99,6 @@ docker-compose up -d

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

The `DEBUG` option when `true` will not generate cache!

## ⚙️ Customization

The configurations are organized in `data/`:
Expand Down Expand Up @@ -194,23 +192,32 @@ Important settings:

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`).

### Error monitoring
### Logging System

Logs are stored in `app/logs/app.log` with automatic 7-day rotation.

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:
Log settings available in `.env` or docker:

```env
HAWK_TOKEN=your_token
LOG_LEVEL=WARNING
```

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).
Available log levels:
- DEBUG: Detailed information for debugging
- INFO: General operational information
- WARNING: Warnings that deserve attention (default)
- ERROR: Errors that don't stop operation
- CRITICAL: Critical errors that need immediate attention

## 🛠️ Maintenance

### Logs

See what's happening:
View application logs:
```bash
docker-compose logs app
# or directly from the log file
cat app/logs/app.log
```

### Clearing the cache
Expand Down
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ SITE_NAME="Marreta"
SITE_DESCRIPTION="Chapéu de paywall é marreta!"
SITE_URL=http://localhost
DNS_SERVERS=1.1.1.1,8.8.8.8
DEBUG=true
LOG_LEVEL=WARNING
SELENIUM_HOST=selenium-hub:4444
LANGUAGE=pt-br
```
Expand All @@ -99,8 +99,6 @@ docker-compose up -d

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

A opção de `DEBUG` quando `true` não irá gerar cache!

## ⚙️ Personalizando

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

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`).

### Monitoramento de erros
### Sistema de Logs

Os logs são armazenados em `app/logs/app.log` com rotação automática a cada 7 dias.

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:
Configurações de log disponíveis no `.env` ou docker:

```env
HAWK_TOKEN=seu_token
LOG_LEVEL=WARNING
```

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).
Níveis de log disponíveis:
- DEBUG: Informações detalhadas para debug
- INFO: Informações gerais sobre operações
- WARNING: Avisos que merecem atenção (padrão)
- ERROR: Erros que não interrompem a operação
- CRITICAL: Erros críticos que precisam de atenção imediata

## 🛠️ Manutenção

### Logs

Ver o que tá acontecendo:
Ver os logs da aplicação:
```bash
docker-compose logs app
# ou diretamente do arquivo de log
cat app/logs/app.log
```

### Limpando o cache
Expand Down
2 changes: 1 addition & 1 deletion app/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"aws/aws-sdk-php": "^3.0",
"php-curl-class/php-curl-class": "^11.0",
"php-webdriver/webdriver": "^1.15",
"codex-team/hawk.php": "^2.2"
"monolog/monolog": "^3.8.1"
},
"autoload": {
"psr-4": {
Expand Down
9 changes: 4 additions & 5 deletions app/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@
filter_var($_ENV['DISABLE_CACHE'], FILTER_VALIDATE_BOOLEAN) : false);
define('SELENIUM_HOST', $_ENV['SELENIUM_HOST'] ?? 'localhost:4444');
define('CACHE_DIR', __DIR__ . '/cache');
define('DEBUG', isset($_ENV['DEBUG']) ?
filter_var($_ENV['DEBUG'], FILTER_VALIDATE_BOOLEAN) : false);
define('LANGUAGE', $_ENV['LANGUAGE'] ?? 'pt-br');

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

/**
* Hawk.so settings
* Configurações do Hawk.so
* Logging settings
* Configurações de log
*/
define('HAWK_TOKEN', $_ENV['HAWK_TOKEN'] ?? null);
define('LOG_LEVEL', $_ENV['LOG_LEVEL'] ?? 'WARNING'); // Available: DEBUG, INFO, WARNING, ERROR, CRITICAL
define('LOG_DAYS_TO_KEEP', 7);

/**
* S3 Cache settings
Expand Down
123 changes: 88 additions & 35 deletions app/inc/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@

namespace Inc;

use Monolog\Logger as MonologLogger;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Level;
use Exception;
use \Hawk\Catcher;

/**
* Error logging and monitoring class
* Classe de monitoramento e registro de erros
*
* This class implements error logging functionality using Hawk.so
* This class implements error logging functionality using Monolog
* for monitoring and tracking application errors.
*
* Esta classe implementa funcionalidades de registro de erros usando Hawk.so
* Esta classe implementa funcionalidades de registro de erros usando Monolog
* para monitoramento e rastreamento de erros da aplicação.
*/
class Logger
Expand All @@ -23,20 +27,59 @@ class Logger
*/
private static $instance = null;

/**
* @var MonologLogger Monolog logger instance
* @var MonologLogger Instância do logger Monolog
*/
private $logger;

/**
* @var array Log level mapping
* @var array Mapeamento de níveis de log
*/
private $logLevels = [
'DEBUG' => \Monolog\Level::Debug,
'INFO' => \Monolog\Level::Info,
'WARNING' => \Monolog\Level::Warning,
'ERROR' => \Monolog\Level::Error,
'CRITICAL' => \Monolog\Level::Critical
];

/**
* Private constructor to prevent direct instantiation
* Construtor privado para prevenir instanciação direta
*
* Initializes Hawk monitoring
* Inicializa o monitoramento Hawk
* Initializes Monolog logger with file rotation
* Inicializa o logger Monolog com rotação de arquivos
*/
private function __construct()
{
// Initialize Hawk
// Inicializa o Hawk
Catcher::init([
'integrationToken' => HAWK_TOKEN,
]);
$this->logger = new MonologLogger('marreta');

// Setup rotating file handler with 7 days retention
// Configura manipulador de arquivo rotativo com retenção de 7 dias
$handler = new RotatingFileHandler(
__DIR__ . '/../logs/app.log',
LOG_DAYS_TO_KEEP,
$this->getLogLevel()
);

// Custom line format
// Formato de linha personalizado
$dateFormat = "Y-m-d H:i:s";
$output = "[%datetime%] %level_name%: %message% %context% %extra%\n";
$formatter = new LineFormatter($output, $dateFormat);
$handler->setFormatter($formatter);

$this->logger->pushHandler($handler);

// If LOG_LEVEL is DEBUG, also log to stderr
// Se LOG_LEVEL for DEBUG, também loga no stderr
if (defined('LOG_LEVEL') && LOG_LEVEL === 'DEBUG') {
$streamHandler = new StreamHandler('php://stderr', \Monolog\Level::Debug);
$streamHandler->setFormatter($formatter);
$this->logger->pushHandler($streamHandler);
}
}

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

/**
* Gets configured log level from environment or default
* Obtém nível de log configurado do ambiente ou padrão
*
* @return Level Monolog log level / Nível de log do Monolog
*/
private function getLogLevel(): Level
{
$configLevel = defined('LOG_LEVEL') ? LOG_LEVEL : 'WARNING';
return $this->logLevels[$configLevel] ?? Level::Warning;
}

/**
* Logs a message with context at specified level
* Registra uma mensagem com contexto no nível especificado
*
* @param string $message Log message / Mensagem de log
* @param array $context Additional context data / Dados adicionais de contexto
* @param string $level Log level / Nível de log
*/
public function log(string $message, array $context = [], string $level = 'WARNING'): void
{
$logLevel = $this->logLevels[$level] ?? \Monolog\Level::Warning;
$this->logger->log($logLevel, $message, $context);
}

/**
* Logs an error with context
* Registra um erro com contexto
*
* @param string $message Error message / Mensagem de erro
* @param array $context Additional context data / Dados adicionais de contexto
* @param string $type Error type/category / Tipo/categoria do erro
*/
public function error(string $message, array $context = [], string $type = 'WARNING'): void
public function error(string $message, array $context = []): void
{
// Log to Hawk
// Registra no Hawk
try {
Catcher::get()->sendException(new Exception($message), [
'type' => $type,
'context' => $context
]);
} catch (Exception $e) {
// If Hawk fails, we already have file logging as backup
// Se o Hawk falhar, já temos o log em arquivo como backup
error_log("Failed to send error to Hawk / Falha ao enviar erro para o Hawk: " . $e->getMessage());
}
$this->log($message, $context, 'ERROR');
}

/**
Expand All @@ -84,21 +141,17 @@ public function error(string $message, array $context = [], string $type = 'WARN
* @param string $url The URL that generated the error / A URL que gerou o erro
* @param string $error_group Error group/category / Grupo/categoria do erro
* @param string $message_error Additional error details / Detalhes adicionais do erro
* @param string $type Error type/category / Tipo/categoria do erro
* @param string $level Log level / Nível de log
*/
public function log(string $url, string $error_group, string $message_error = '', string $type = 'WARNING'): void
public function logUrl(string $url, string $error_group, string $message_error = '', string $level = 'WARNING'): void
{
// If no Hawk token is configured, don't generate log
// Se não houver token do Hawk configurado, não gera log
if (empty(HAWK_TOKEN)) {
return;
}

$this->error($error_group, [
$context = [
'url' => $url,
'timestamp' => time(),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
'message_error' => $message_error
], $type);
];

$this->log($error_group, $context, $level);
}
}
}
4 changes: 2 additions & 2 deletions app/inc/URLAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -814,8 +814,8 @@ private function addBrandBar($dom, $xpath)
$brandDiv->appendChild($brandHtml);
$body->appendChild($brandDiv);

// Add debug panel if DEBUG is true / Adicionar painel de depuração se DEBUG for verdadeiro
if (DEBUG) {
// Add debug panel if LOG_LEVEL is DEBUG / Adicionar painel de depuração se LOG_LEVEL for DEBUG
if (LOG_LEVEL === 'DEBUG') {
$debugDiv = $dom->createElement('div');
$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;');

Expand Down
5 changes: 3 additions & 2 deletions default.conf
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ server {

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

location / {
Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ services:
- SITE_URL=${SITE_URL:-https://marreta.localhost}
- DNS_SERVERS=${DNS_SERVER:-}
- LANGUAGE=${LANGUAGE:-}
- DEBUG=${DEBUG:-}
- LOG_LEVEL=${LOG_LEVEL:-WARNING}
- SELENIUM_HOST=${SELENIUM_HOST:-selenium-hub:4444}
restart: unless-stopped
selenium-chromium:
Expand Down Expand Up @@ -57,4 +57,4 @@ services:
ports:
- 4442:4442
- 4443:4443
- 4444:4444
- 4444:4444

0 comments on commit 4cd475c

Please sign in to comment.