Skip to content

Commit

Permalink
Merge pull request #53 from hhxsv5/master
Browse files Browse the repository at this point in the history
Add debug mode && logging
  • Loading branch information
hhxsv5 authored May 9, 2019
2 parents c9ab87e + 34ac6c0 commit a9e67e3
Show file tree
Hide file tree
Showing 9 changed files with 165 additions and 15 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ composer require "kucoin/kucoin-php-sdk:~1.1.0"
KuCoinApi::setBaseUri('https://openapi-sandbox.kucoin.com');
```

### Debug mode & logging

```php
// Debug mode will record the logs of API and WebSocket to files in the directory "KuCoinApi::getDefaultLogPath()" according to the minimum log level "KuCoinApi::getLogLevel()".
KuCoinApi::setDebugMode(true);

// Logging in your code
// KuCoinApi::setLogPath('/tmp');
// KuCoinApi::setLogLevel(Monolog\Logger::DEBUG);
KuCoinApi::getLogger()->debug('I\'am a debug message');
```

### Examples
> See the [test case](tests) for more examples.
Expand Down Expand Up @@ -251,6 +263,12 @@ go(function () {
> Modify your API key in `phpunit.xml` first.
```shell
# Add your API configuration items into the environmental variable first
export API_BASE_URI=https://openapi-v2.kucoin.com
export API_KEY=key
export API_SECRET=secret
export API_PASSPHRASE=passphrase

composer test
```

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"php": ">=5.5.0",
"ext-json": "*",
"guzzlehttp/guzzle": "~6.0",
"ratchet/pawl": "^0.3.2"
"ratchet/pawl": "^0.3.2",
"monolog/monolog": "^1.24"
},
"require-dev": {
"phpunit/phpunit": "^5.7"
Expand Down
105 changes: 105 additions & 0 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
use KuCoin\SDK\Http\IHttp;
use KuCoin\SDK\Http\Request;
use KuCoin\SDK\Http\Response;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

abstract class Api
{
Expand All @@ -19,6 +23,26 @@ abstract class Api
*/
protected static $skipVerifyTls = false;

/**
* @var bool
*/
protected static $debugMode = false;

/**
* @var string
*/
protected static $logPath = '/tmp';

/**
* @var LoggerInterface $logger
*/
protected static $logger;

/**
* @var int
*/
protected static $logLevel = Logger::DEBUG;

/**
* @var IAuth $auth
*/
Expand Down Expand Up @@ -70,6 +94,78 @@ public static function setSkipVerifyTls($skipVerifyTls)
static::$skipVerifyTls = $skipVerifyTls;
}

/**
* @return bool
*/
public static function isDebugMode()
{
return self::$debugMode;
}

/**
* @param bool $debugMode
*/
public static function setDebugMode($debugMode)
{
self::$debugMode = $debugMode;
}

/**
* @param LoggerInterface $logger
*/
public static function setLogger(LoggerInterface $logger)
{
self::$logger = $logger;
}

/**
* @return Logger|LoggerInterface
* @throws \Exception
*/
public static function getLogger()
{
if (self::$logger === null) {
self::$logger = new Logger('kucoin-sdk');
$handler = new RotatingFileHandler(static::getLogPath() . '/kucoin-sdk.log', 0, static::$logLevel);
$formatter = new LineFormatter(null, null, false, true);
$handler->setFormatter($formatter);
self::$logger->pushHandler($handler);
}
return self::$logger;
}

/**
* @return string
*/
public static function getLogPath()
{
return self::$logPath;
}

/**
* @param string $logPath
*/
public static function setLogPath($logPath)
{
self::$logPath = $logPath;
}

/**
* @return int
*/
public static function getLogLevel()
{
return self::$logLevel;
}

/**
* @param int $logLevel
*/
public static function setLogLevel($logLevel)
{
self::$logLevel = $logLevel;
}

/**
* @param string $method
* @param string $uri
Expand Down Expand Up @@ -98,7 +194,16 @@ public function call($method, $uri, array $params = [], array $headers = [], $ti
}
$request->setHeaders($headers);

$requestId = uniqid();

if (self::isDebugMode()) {
static::getLogger()->debug(sprintf('Sent a HTTP request#%s: %s', $requestId, $request));
}
$response = $this->http->request($request, $timeout);
if (self::isDebugMode()) {
static::getLogger()->debug(sprintf('Received a HTTP response#%s: %s', $requestId, $response));
}

return $response;
}
}
8 changes: 8 additions & 0 deletions src/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,12 @@ protected function isGetOrDeleteMethod()
{
return in_array($this->getMethod(), [self::METHOD_GET, self::METHOD_DELETE], true);
}

public function __toString()
{
$str = $this->getMethod() . ' ' . $this->getRequestUri();
$str .= ' with headers=' . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$str .= ' with body=' . $this->getBodyParams();
return $str;
}
}
8 changes: 8 additions & 0 deletions src/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,12 @@ public function isSuccessful()
return $this->statusCode == 200;
}

public function __toString()
{
$str = 'respond ' . $this->getStatusCode();
$str .= ' with headers=' . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$str .= ' with body=' . $this->getBody(false);
return $str;
}

}
7 changes: 7 additions & 0 deletions src/Http/SwooleHttp.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@
use Swlib\Http\ContentType;
use Swlib\Http\Exception\RequestException;
use Swlib\Saber;
use Swoole\Runtime;

class SwooleHttp extends BaseHttp
{
protected static $clients = [];

public function __construct(array $config = [])
{
parent::__construct($config);
Runtime::enableCoroutine();
}

/**
* @param array $config
* @return Saber
Expand Down
9 changes: 8 additions & 1 deletion src/PrivateApi/WebSocketFeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,21 @@ public function subscribeChannels(array $server, array $channels, callable $onMe
$pingTimer = $loop->addPeriodicTimer($server['pingInterval'] / 1000 - 1, function () use ($ws) {
try {
$ping = $this->createPingMessage();
$pingStr = json_encode($ping);
if (self::isDebugMode()) {
static::getLogger()->debug(sprintf('Sent a WebSocket message: %s', $pingStr));
}
// fputs(STDIN, print_r($ping, true));
$ws->send(json_encode($ping));
$ws->send($pingStr);
} catch (\Exception $e) {
// Ignore this exception
}
});
$ws->on('message', function (MessageInterface $msg) use ($server, $ws, $channels, $onMessage, $loop, $pingTimer) {
$msgStr = $msg->__toString();
if (self::isDebugMode()) {
static::getLogger()->debug(sprintf('Received a WebSocket message: %s', $msgStr));
}
$msgArray = json_decode($msgStr, true);
if (!isset($msgArray['type'])) {
throw new BusinessException('Invalid format of message without type: ' . $msgStr);
Expand Down
2 changes: 2 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ public function apiProvider()
$apiPassPhrase = getenv('API_PASSPHRASE');
$apiBaseUri = getenv('API_BASE_URI');
$apiSkipVerifyTls = (bool)getenv('API_SKIP_VERIFY_TLS');
$apiDebugMode = (bool)getenv('API_DEBUG_MODE');
KuCoinApi::setSkipVerifyTls($apiSkipVerifyTls);
KuCoinApi::setDebugMode($apiDebugMode);
if ($apiBaseUri) {
KuCoinApi::setBaseUri($apiBaseUri);
}
Expand Down
20 changes: 7 additions & 13 deletions tests/WebSocketFeedTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ public function testGetPrivateBullet(WebSocketFeed $api)
public function testSubscribePublicChannel(WebSocketFeed $api)
{
$query = ['connectId' => uniqid('', true),];
$channel = [
'topic' => '/market/ticker:KCS-BTC',
//'response' => true,
];
$channel = ['topic' => '/market/ticker:KCS-BTC'];

$options = [
// 'tls' => [
Expand Down Expand Up @@ -104,8 +101,8 @@ public function testSubscribePublicChannels(WebSocketFeed $api)
{
$query = ['connectId' => uniqid('', true),];
$channels = [
['topic' => '/market/ticker:KCS-BTC',/*'response' => true,*/],
['topic' => '/market/ticker:ETH-BTC',/*'response' => true,*/],
['topic' => '/market/ticker:KCS-BTC'],
['topic' => '/market/ticker:ETH-BTC'],
];

$options = [
Expand Down Expand Up @@ -136,10 +133,7 @@ public function testSubscribePublicChannels(WebSocketFeed $api)
public function testSubscribePrivateChannel(WebSocketFeed $api)
{
$query = ['connectId' => uniqid('', true),];
$channel = [
'topic' => '/market/match:KCS-BTC',
//'response' => true,
];
$channel = ['topic' => '/market/match:KCS-BTC'];

$options = [
// 'tls' => [
Expand Down Expand Up @@ -169,8 +163,8 @@ public function testSubscribePrivateChannels(WebSocketFeed $api)
{
$query = ['connectId' => uniqid('', true),];
$channels = [
['topic' => '/market/match:KCS-BTC',/*'response' => true,*/],
['topic' => '/market/match:ETH-BTC',/*'response' => true,*/],
['topic' => '/market/match:KCS-BTC'],
['topic' => '/market/match:ETH-BTC'],
];

$options = [
Expand All @@ -191,4 +185,4 @@ public function testSubscribePrivateChannels(WebSocketFeed $api)
echo "OnClose: {$code} {$reason}\n";
}, $options);
}
}
}

0 comments on commit a9e67e3

Please sign in to comment.