Skip to content

Commit a9e67e3

Browse files
authored
Merge pull request #53 from hhxsv5/master
Add debug mode && logging
2 parents c9ab87e + 34ac6c0 commit a9e67e3

File tree

9 files changed

+165
-15
lines changed

9 files changed

+165
-15
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@ composer require "kucoin/kucoin-php-sdk:~1.1.0"
3838
KuCoinApi::setBaseUri('https://openapi-sandbox.kucoin.com');
3939
```
4040

41+
### Debug mode & logging
42+
43+
```php
44+
// 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()".
45+
KuCoinApi::setDebugMode(true);
46+
47+
// Logging in your code
48+
// KuCoinApi::setLogPath('/tmp');
49+
// KuCoinApi::setLogLevel(Monolog\Logger::DEBUG);
50+
KuCoinApi::getLogger()->debug('I\'am a debug message');
51+
```
52+
4153
### Examples
4254
> See the [test case](tests) for more examples.
4355
@@ -251,6 +263,12 @@ go(function () {
251263
> Modify your API key in `phpunit.xml` first.
252264
253265
```shell
266+
# Add your API configuration items into the environmental variable first
267+
export API_BASE_URI=https://openapi-v2.kucoin.com
268+
export API_KEY=key
269+
export API_SECRET=secret
270+
export API_PASSPHRASE=passphrase
271+
254272
composer test
255273
```
256274

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
"php": ">=5.5.0",
2424
"ext-json": "*",
2525
"guzzlehttp/guzzle": "~6.0",
26-
"ratchet/pawl": "^0.3.2"
26+
"ratchet/pawl": "^0.3.2",
27+
"monolog/monolog": "^1.24"
2728
},
2829
"require-dev": {
2930
"phpunit/phpunit": "^5.7"

src/Api.php

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
use KuCoin\SDK\Http\IHttp;
77
use KuCoin\SDK\Http\Request;
88
use KuCoin\SDK\Http\Response;
9+
use Monolog\Formatter\LineFormatter;
10+
use Monolog\Handler\RotatingFileHandler;
11+
use Monolog\Logger;
12+
use Psr\Log\LoggerInterface;
913

1014
abstract class Api
1115
{
@@ -19,6 +23,26 @@ abstract class Api
1923
*/
2024
protected static $skipVerifyTls = false;
2125

26+
/**
27+
* @var bool
28+
*/
29+
protected static $debugMode = false;
30+
31+
/**
32+
* @var string
33+
*/
34+
protected static $logPath = '/tmp';
35+
36+
/**
37+
* @var LoggerInterface $logger
38+
*/
39+
protected static $logger;
40+
41+
/**
42+
* @var int
43+
*/
44+
protected static $logLevel = Logger::DEBUG;
45+
2246
/**
2347
* @var IAuth $auth
2448
*/
@@ -70,6 +94,78 @@ public static function setSkipVerifyTls($skipVerifyTls)
7094
static::$skipVerifyTls = $skipVerifyTls;
7195
}
7296

97+
/**
98+
* @return bool
99+
*/
100+
public static function isDebugMode()
101+
{
102+
return self::$debugMode;
103+
}
104+
105+
/**
106+
* @param bool $debugMode
107+
*/
108+
public static function setDebugMode($debugMode)
109+
{
110+
self::$debugMode = $debugMode;
111+
}
112+
113+
/**
114+
* @param LoggerInterface $logger
115+
*/
116+
public static function setLogger(LoggerInterface $logger)
117+
{
118+
self::$logger = $logger;
119+
}
120+
121+
/**
122+
* @return Logger|LoggerInterface
123+
* @throws \Exception
124+
*/
125+
public static function getLogger()
126+
{
127+
if (self::$logger === null) {
128+
self::$logger = new Logger('kucoin-sdk');
129+
$handler = new RotatingFileHandler(static::getLogPath() . '/kucoin-sdk.log', 0, static::$logLevel);
130+
$formatter = new LineFormatter(null, null, false, true);
131+
$handler->setFormatter($formatter);
132+
self::$logger->pushHandler($handler);
133+
}
134+
return self::$logger;
135+
}
136+
137+
/**
138+
* @return string
139+
*/
140+
public static function getLogPath()
141+
{
142+
return self::$logPath;
143+
}
144+
145+
/**
146+
* @param string $logPath
147+
*/
148+
public static function setLogPath($logPath)
149+
{
150+
self::$logPath = $logPath;
151+
}
152+
153+
/**
154+
* @return int
155+
*/
156+
public static function getLogLevel()
157+
{
158+
return self::$logLevel;
159+
}
160+
161+
/**
162+
* @param int $logLevel
163+
*/
164+
public static function setLogLevel($logLevel)
165+
{
166+
self::$logLevel = $logLevel;
167+
}
168+
73169
/**
74170
* @param string $method
75171
* @param string $uri
@@ -98,7 +194,16 @@ public function call($method, $uri, array $params = [], array $headers = [], $ti
98194
}
99195
$request->setHeaders($headers);
100196

197+
$requestId = uniqid();
198+
199+
if (self::isDebugMode()) {
200+
static::getLogger()->debug(sprintf('Sent a HTTP request#%s: %s', $requestId, $request));
201+
}
101202
$response = $this->http->request($request, $timeout);
203+
if (self::isDebugMode()) {
204+
static::getLogger()->debug(sprintf('Received a HTTP response#%s: %s', $requestId, $response));
205+
}
206+
102207
return $response;
103208
}
104209
}

src/Http/Request.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,4 +166,12 @@ protected function isGetOrDeleteMethod()
166166
{
167167
return in_array($this->getMethod(), [self::METHOD_GET, self::METHOD_DELETE], true);
168168
}
169+
170+
public function __toString()
171+
{
172+
$str = $this->getMethod() . ' ' . $this->getRequestUri();
173+
$str .= ' with headers=' . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
174+
$str .= ' with body=' . $this->getBodyParams();
175+
return $str;
176+
}
169177
}

src/Http/Response.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,12 @@ public function isSuccessful()
6161
return $this->statusCode == 200;
6262
}
6363

64+
public function __toString()
65+
{
66+
$str = 'respond ' . $this->getStatusCode();
67+
$str .= ' with headers=' . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
68+
$str .= ' with body=' . $this->getBody(false);
69+
return $str;
70+
}
71+
6472
}

src/Http/SwooleHttp.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,18 @@
77
use Swlib\Http\ContentType;
88
use Swlib\Http\Exception\RequestException;
99
use Swlib\Saber;
10+
use Swoole\Runtime;
1011

1112
class SwooleHttp extends BaseHttp
1213
{
1314
protected static $clients = [];
1415

16+
public function __construct(array $config = [])
17+
{
18+
parent::__construct($config);
19+
Runtime::enableCoroutine();
20+
}
21+
1522
/**
1623
* @param array $config
1724
* @return Saber

src/PrivateApi/WebSocketFeed.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,14 +115,21 @@ public function subscribeChannels(array $server, array $channels, callable $onMe
115115
$pingTimer = $loop->addPeriodicTimer($server['pingInterval'] / 1000 - 1, function () use ($ws) {
116116
try {
117117
$ping = $this->createPingMessage();
118+
$pingStr = json_encode($ping);
119+
if (self::isDebugMode()) {
120+
static::getLogger()->debug(sprintf('Sent a WebSocket message: %s', $pingStr));
121+
}
118122
// fputs(STDIN, print_r($ping, true));
119-
$ws->send(json_encode($ping));
123+
$ws->send($pingStr);
120124
} catch (\Exception $e) {
121125
// Ignore this exception
122126
}
123127
});
124128
$ws->on('message', function (MessageInterface $msg) use ($server, $ws, $channels, $onMessage, $loop, $pingTimer) {
125129
$msgStr = $msg->__toString();
130+
if (self::isDebugMode()) {
131+
static::getLogger()->debug(sprintf('Received a WebSocket message: %s', $msgStr));
132+
}
126133
$msgArray = json_decode($msgStr, true);
127134
if (!isset($msgArray['type'])) {
128135
throw new BusinessException('Invalid format of message without type: ' . $msgStr);

tests/TestCase.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ public function apiProvider()
1919
$apiPassPhrase = getenv('API_PASSPHRASE');
2020
$apiBaseUri = getenv('API_BASE_URI');
2121
$apiSkipVerifyTls = (bool)getenv('API_SKIP_VERIFY_TLS');
22+
$apiDebugMode = (bool)getenv('API_DEBUG_MODE');
2223
KuCoinApi::setSkipVerifyTls($apiSkipVerifyTls);
24+
KuCoinApi::setDebugMode($apiDebugMode);
2325
if ($apiBaseUri) {
2426
KuCoinApi::setBaseUri($apiBaseUri);
2527
}

tests/WebSocketFeedTest.php

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,7 @@ public function testGetPrivateBullet(WebSocketFeed $api)
7070
public function testSubscribePublicChannel(WebSocketFeed $api)
7171
{
7272
$query = ['connectId' => uniqid('', true),];
73-
$channel = [
74-
'topic' => '/market/ticker:KCS-BTC',
75-
//'response' => true,
76-
];
73+
$channel = ['topic' => '/market/ticker:KCS-BTC'];
7774

7875
$options = [
7976
// 'tls' => [
@@ -104,8 +101,8 @@ public function testSubscribePublicChannels(WebSocketFeed $api)
104101
{
105102
$query = ['connectId' => uniqid('', true),];
106103
$channels = [
107-
['topic' => '/market/ticker:KCS-BTC',/*'response' => true,*/],
108-
['topic' => '/market/ticker:ETH-BTC',/*'response' => true,*/],
104+
['topic' => '/market/ticker:KCS-BTC'],
105+
['topic' => '/market/ticker:ETH-BTC'],
109106
];
110107

111108
$options = [
@@ -136,10 +133,7 @@ public function testSubscribePublicChannels(WebSocketFeed $api)
136133
public function testSubscribePrivateChannel(WebSocketFeed $api)
137134
{
138135
$query = ['connectId' => uniqid('', true),];
139-
$channel = [
140-
'topic' => '/market/match:KCS-BTC',
141-
//'response' => true,
142-
];
136+
$channel = ['topic' => '/market/match:KCS-BTC'];
143137

144138
$options = [
145139
// 'tls' => [
@@ -169,8 +163,8 @@ public function testSubscribePrivateChannels(WebSocketFeed $api)
169163
{
170164
$query = ['connectId' => uniqid('', true),];
171165
$channels = [
172-
['topic' => '/market/match:KCS-BTC',/*'response' => true,*/],
173-
['topic' => '/market/match:ETH-BTC',/*'response' => true,*/],
166+
['topic' => '/market/match:KCS-BTC'],
167+
['topic' => '/market/match:ETH-BTC'],
174168
];
175169

176170
$options = [
@@ -191,4 +185,4 @@ public function testSubscribePrivateChannels(WebSocketFeed $api)
191185
echo "OnClose: {$code} {$reason}\n";
192186
}, $options);
193187
}
194-
}
188+
}

0 commit comments

Comments
 (0)