Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace app\services\Log;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Log\LogLevel;
- /**
- * Debug console logger that outputs formatted logs directly to console
- * Useful for live debugging in production environments without modifying log files
- */
- class DebugConsoleLogger extends LoggerService
- {
- // ANSI color codes for console output
- private const COLORS = [
- LogLevel::ERROR => "\033[31m", // Red
- LogLevel::WARNING => "\033[33m", // Yellow
- LogLevel::INFO => "\033[32m", // Green
- LogLevel::DEBUG => "\033[36m", // Cyan
- 'reset' => "\033[0m", // Reset
- 'bold' => "\033[1m", // Bold
- 'dim' => "\033[2m", // Dim
- ];
- /**
- * Format and output log message to console
- */
- public function log($level, LogChannels $channel, $message, array $context = [], ?\Throwable $e = null, ?ResponseInterface $response = null): void
- {
- // Add exception and response to context if provided
- if ($e) {
- $context['exception'] = [
- 'class' => get_class($e),
- 'message' => $e->getMessage(),
- 'code' => $e->getCode(),
- 'file' => $e->getFile() . ':' . $e->getLine(),
- 'trace' => $this->formatTrace($e->getTraceAsString())
- ];
- }
- if ($response) {
- $context['response'] = [
- 'status' => $response->getStatusCode(),
- 'reason' => $response->getReasonPhrase(),
- 'body' => $this->truncateResponseBody((string)$response->getBody())
- ];
- }
- // Format the output
- $timestamp = (new \DateTimeImmutable())->format('Y-m-d H:i:s.u');
- $color = self::COLORS[$level] ?? self::COLORS[LogLevel::INFO];
- $reset = self::COLORS['reset'];
- $bold = self::COLORS['bold'];
- $dim = self::COLORS['dim'];
- // Format the log line
- echo sprintf(
- "%s%s%s [%s%s%s] [%s%s%s]: %s%s%s\n",
- $dim, $timestamp, $reset,
- $color, strtoupper($level), $reset,
- $bold, $channel->name, $reset,
- $color, $message, $reset
- );
- // Output context if not empty
- if (!empty($context)) {
- $contextOutput = $this->formatContext($context);
- echo $contextOutput . "\n";
- }
- // Add an empty line for better readability between log entries
- echo "\n";
- }
- /**
- * Format context array for console output
- */
- private function formatContext(array $context, int $indent = 2): string
- {
- $output = '';
- $indentStr = str_repeat(' ', $indent);
- foreach ($context as $key => $value) {
- $output .= $indentStr . $key . ': ';
- if (is_array($value)) {
- $output .= "\n" . $this->formatContext($value, $indent + 2);
- } elseif (is_object($value)) {
- if (method_exists($value, '__toString')) {
- $output .= (string)$value . "\n";
- } else {
- $output .= get_class($value) . "\n";
- }
- } elseif (is_bool($value)) {
- $output .= ($value ? 'true' : 'false') . "\n";
- } elseif (is_null($value)) {
- $output .= "null\n";
- } else {
- $output .= $value . "\n";
- }
- }
- return $output;
- }
- /**
- * Format stack trace for better readability
- */
- private function formatTrace(string $trace): string
- {
- $lines = explode("\n", $trace);
- // Just return first few lines to avoid overwhelming output
- return implode("\n", array_slice($lines, 0, 5)) . (count($lines) > 5 ? "\n..." : "");
- }
- /**
- * Truncate response body if too long
- */
- private function truncateResponseBody(string $body, int $maxLength = 500): string
- {
- if (strlen($body) <= $maxLength) {
- return $body;
- }
- return substr($body, 0, $maxLength) . '... [truncated, total length: ' . strlen($body) . ' bytes]';
- }
- // Shortcut methods for each log level
- public function info(LogChannels $channel, $message, array $context = [], ?\Throwable $e = null, ?ResponseInterface $response = null): void
- {
- $this->log(LogLevel::INFO, $channel, $message, $context, $e, $response);
- }
- public function debug(LogChannels $channel, $message, array $context = [], ?\Throwable $e = null, ?ResponseInterface $response = null): void
- {
- $this->log(LogLevel::DEBUG, $channel, $message, $context, $e, $response);
- }
- public function error(LogChannels $channel, $message, array $context = [], ?\Throwable $e = null, ?ResponseInterface $response = null): void
- {
- $this->log(LogLevel::ERROR, $channel, $message, $context, $e, $response);
- }
- public function warning(LogChannels $channel, $message, array $context = [], ?\Throwable $e = null, ?ResponseInterface $response = null): void
- {
- $this->log(LogLevel::WARNING, $channel, $message, $context, $e, $response);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement