| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace Libs;
- /**
- * Logger simples da aplicação.
- *
- * - Escreve no terminal (STDERR) para visibilidade imediata em desenvolvimento.
- * - Escreve também em arquivo (log.txt por padrão) para histórico persistente.
- *
- * Ativado/desativado pela variável de ambiente LOG_ENABLED (true/false).
- * O caminho do arquivo pode ser customizado por LOG_FILE.
- */
- final class Logger
- {
- public const LEVEL_DEBUG = 'debug';
- public const LEVEL_INFO = 'info';
- public const LEVEL_WARNING = 'warning';
- public const LEVEL_ERROR = 'error';
- /**
- * Verifica se o log está habilitado. Default: habilitado.
- */
- public static function isEnabled(): bool
- {
- $flag = $_ENV['LOG_ENABLED'] ?? 'true';
- return filter_var($flag, FILTER_VALIDATE_BOOLEAN);
- }
- public static function debug(string $message, array $context = []): void
- {
- self::log(self::LEVEL_DEBUG, $message, $context);
- }
- public static function info(string $message, array $context = []): void
- {
- self::log(self::LEVEL_INFO, $message, $context);
- }
- public static function warning(string $message, array $context = []): void
- {
- self::log(self::LEVEL_WARNING, $message, $context);
- }
- public static function error(string $message, array $context = []): void
- {
- self::log(self::LEVEL_ERROR, $message, $context);
- }
- /**
- * Registra uma entrada de log no terminal e no arquivo.
- */
- public static function log(string $level, string $message, array $context = []): void
- {
- if (!self::isEnabled()) {
- return;
- }
- $line = self::format($level, $message, $context);
- self::writeToTerminal($line);
- self::writeToFile($line);
- }
- private static function format(string $level, string $message, array $context): string
- {
- $timestamp = date('Y-m-d H:i:s');
- $levelLabel = strtoupper($level);
- $suffix = '';
- if (!empty($context)) {
- $encoded = json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
- $suffix = ' ' . ($encoded !== false ? $encoded : '[context not serializable]');
- }
- return sprintf('[%s] %s: %s%s', $timestamp, $levelLabel, $message, $suffix);
- }
- private static function writeToTerminal(string $line): void
- {
- if (defined('STDERR')) {
- fwrite(STDERR, $line . PHP_EOL);
- return;
- }
- error_log($line);
- }
- private static function writeToFile(string $line): void
- {
- $file = $_ENV['LOG_FILE'] ?? (dirname(__DIR__) . '/log.txt');
- // Falha de escrita em log não deve derrubar a aplicação.
- @file_put_contents($file, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
- }
- }
|