EchoLog.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. /**
  3. * Simple echo logger (only available when running in dev environment)
  4. */
  5. namespace WebSocket;
  6. class EchoLog implements \Psr\Log\LoggerInterface
  7. {
  8. use \Psr\Log\LoggerTrait;
  9. public function log($level, $message, array $context = [])
  10. {
  11. $message = $this->interpolate($message, $context);
  12. $context_string = empty($context) ? '' : json_encode($context);
  13. echo str_pad($level, 8) . " | {$message} {$context_string}\n";
  14. }
  15. public function interpolate($message, array $context = [])
  16. {
  17. // Build a replacement array with braces around the context keys
  18. $replace = [];
  19. foreach ($context as $key => $val) {
  20. // Check that the value can be cast to string
  21. if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
  22. $replace['{' . $key . '}'] = $val;
  23. }
  24. }
  25. // Interpolate replacement values into the message and return
  26. return strtr($message, $replace);
  27. }
  28. }