laravel-websockets/src/Server/Logger/WebsocketsLogger.php

70 lines
2.0 KiB
PHP
Raw Normal View History

2018-11-24 14:23:59 +00:00
<?php
namespace BeyondCode\LaravelWebSockets\Server\Logger;
2018-11-25 23:42:45 +00:00
use BeyondCode\LaravelWebSockets\QueryParameters;
2018-11-24 14:23:59 +00:00
use Exception;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;
2018-11-30 14:52:11 +00:00
class WebsocketsLogger extends Logger implements MessageComponentInterface
2018-11-24 14:23:59 +00:00
{
/** @var \Ratchet\Http\HttpServerInterface */
protected $app;
2018-11-30 14:52:11 +00:00
public static function decorate(MessageComponentInterface $app): WebsocketsLogger
2018-11-24 14:23:59 +00:00
{
2018-11-30 14:52:11 +00:00
$logger = app(WebsocketsLogger::class);
2018-11-24 14:23:59 +00:00
return $logger->setApp($app);
}
public function setApp(MessageComponentInterface $app)
{
$this->app = $app;
return $this;
}
public function onOpen(ConnectionInterface $connection)
{
2018-11-25 23:42:45 +00:00
$appKey = QueryParameters::create($connection->httpRequest)->get('appKey');
2018-11-24 14:23:59 +00:00
2018-11-25 23:42:45 +00:00
$this->warn("New connection opened for app key {$appKey}.");
2018-11-24 14:23:59 +00:00
$this->app->onOpen(ConnectionLogger::decorate($connection));
}
public function onMessage(ConnectionInterface $connection, MessageInterface $message)
{
2018-12-01 13:12:15 +00:00
$this->info("{$connection->app->id}: connection id {$connection->socketId} received message: {$message->getPayload()}.");
2018-11-24 14:23:59 +00:00
$this->app->onMessage(ConnectionLogger::decorate($connection), $message);
}
public function onClose(ConnectionInterface $connection)
{
2018-11-27 21:56:45 +00:00
$this->warn("Connection id {$connection->socketId} closed.");
2018-11-24 14:23:59 +00:00
$this->app->onClose(ConnectionLogger::decorate($connection));
}
public function onError(ConnectionInterface $connection, Exception $exception)
{
$exceptionClass = get_class($exception);
2018-12-01 13:12:15 +00:00
$appId = $connection->app->id ?? 'Unknown app id';
2018-11-24 14:23:59 +00:00
2018-11-27 20:43:44 +00:00
$message = "{$appId}: exception `{$exceptionClass}` thrown: `{$exception->getMessage()}`.";
2018-11-24 14:23:59 +00:00
if ($this->verbose) {
$message .= $exception->getTraceAsString();
}
$this->error($message);
$this->app->onError(ConnectionLogger::decorate($connection), $exception);
}
}