Skip to content

Commit 09b0df1

Browse files
committed
Make logger more flexible and allow passing of parameters in a sprintf style.
1 parent b12b2e9 commit 09b0df1

File tree

6 files changed

+60
-32
lines changed

6 files changed

+60
-32
lines changed

examples/Commands/ShortenerCommand.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public function execute()
4040
$data = [];
4141
$data['chat_id'] = $chat_id;
4242

43-
$text = Botan::shortenUrl("https://github.com/akalongman/php-telegram-bot", $user_id);
43+
$text = Botan::shortenUrl('https://github.com/akalongman/php-telegram-bot', $user_id);
4444

4545
$data['text'] = $text;
4646

src/Botan.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ public static function track(Update $update, $command = '')
191191
$responseData = json_decode($result, true);
192192

193193
if (!$responseData || $responseData['status'] !== 'accepted') {
194-
TelegramLog::debug('Botan.io stats report failed: ' . ($result ?: 'empty response'));
194+
TelegramLog::debug('Botan.io stats report failed: %s', $result ?: 'empty response');
195195

196196
return false;
197197
}
@@ -238,7 +238,7 @@ public static function shortenUrl($url, $user_id)
238238
}
239239

240240
if (filter_var($result, FILTER_VALIDATE_URL) === false) {
241-
TelegramLog::debug('Botan.io URL shortening failed for "' . $url . '": ' . ($result ?: 'empty response'));
241+
TelegramLog::debug('Botan.io URL shortening failed for "%s": %s', $url, $result ?: 'empty response');
242242

243243
return $url;
244244
}

src/Entities/Message.php

+9-9
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ public function getFullCommand()
152152
{
153153
$text = $this->getProperty('text');
154154
if (strpos($text, '/') === 0) {
155-
$no_EOL = strtok($text, PHP_EOL);
155+
$no_EOL = strtok($text, PHP_EOL);
156156
$no_space = strtok($text, ' ');
157157

158158
//try to understand which separator \n or space divide /command from text
@@ -174,21 +174,21 @@ public function getCommand()
174174
return $command;
175175
}
176176

177-
$cmd = $this->getFullCommand();
177+
$full_command = $this->getFullCommand();
178178

179-
if (strpos($cmd, '/') === 0) {
180-
$cmd = substr($cmd, 1);
179+
if (strpos($full_command, '/') === 0) {
180+
$full_command = substr($full_command, 1);
181181

182182
//check if command is follow by botname
183-
$split_cmd = explode('@', $cmd);
183+
$split_cmd = explode('@', $full_command);
184184
if (isset($split_cmd[1])) {
185185
//command is followed by name check if is addressed to me
186186
if (strtolower($split_cmd[1]) === strtolower($this->getBotName())) {
187187
return $split_cmd[0];
188188
}
189189
} else {
190190
//command is not followed by name
191-
return $cmd;
191+
return $full_command;
192192
}
193193
}
194194

@@ -208,10 +208,10 @@ public function getText($without_cmd = false)
208208

209209
if ($without_cmd && $command = $this->getFullCommand()) {
210210
if (strlen($command) + 1 < strlen($text)) {
211-
$text = substr($text, strlen($command) + 1);
212-
} else {
213-
$text = '';
211+
return substr($text, strlen($command) + 1);
214212
}
213+
214+
return '';
215215
}
216216

217217
return $text;

src/Telegram.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ public function enableAdmin($admin_id)
499499
if (is_int($admin_id) && $admin_id > 0 && !in_array($admin_id, $this->admins_list, true)) {
500500
$this->admins_list[] = $admin_id;
501501
} else {
502-
TelegramLog::error('Invalid value "' . $admin_id . '" for admin.');
502+
TelegramLog::error('Invalid value "%s" for admin.', $admin_id);
503503
}
504504

505505
return $this;
@@ -590,7 +590,7 @@ public function isDbEnabled()
590590
public function addCommandsPath($path, $before = true)
591591
{
592592
if (!is_dir($path)) {
593-
TelegramLog::error('Commands path "' . $path . '" does not exist.');
593+
TelegramLog::error('Commands path "%s" does not exist.', $path);
594594
} elseif (!in_array($path, $this->commands_paths, true)) {
595595
if ($before) {
596596
array_unshift($this->commands_paths, $path);

src/TelegramLog.php

+24-9
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,7 @@ public static function endDebugLogTempStream($message = '%s')
165165
{
166166
if (is_resource(self::$debug_log_temp_stream_handle)) {
167167
rewind(self::$debug_log_temp_stream_handle);
168-
self::debug(
169-
sprintf(
170-
$message,
171-
stream_get_contents(self::$debug_log_temp_stream_handle)
172-
)
173-
);
168+
self::debug($message, stream_get_contents(self::$debug_log_temp_stream_handle));
174169
fclose(self::$debug_log_temp_stream_handle);
175170
self::$debug_log_temp_stream_handle = null;
176171
}
@@ -218,7 +213,7 @@ public static function initUpdateLog($path)
218213
*/
219214
public static function isErrorLogActive()
220215
{
221-
return (self::$error_log_path !== null);
216+
return self::$error_log_path !== null;
222217
}
223218

224219
/**
@@ -228,7 +223,7 @@ public static function isErrorLogActive()
228223
*/
229224
public static function isDebugLogActive()
230225
{
231-
return (self::$debug_log_path !== null);
226+
return self::$debug_log_path !== null;
232227
}
233228

234229
/**
@@ -238,7 +233,7 @@ public static function isDebugLogActive()
238233
*/
239234
public static function isUpdateLogActive()
240235
{
241-
return (self::$update_log_path !== null);
236+
return self::$update_log_path !== null;
242237
}
243238

244239
/**
@@ -249,6 +244,7 @@ public static function isUpdateLogActive()
249244
public static function error($text)
250245
{
251246
if (self::isErrorLogActive()) {
247+
$text = self::getLogText($text, func_get_args());
252248
self::$monolog->error($text);
253249
}
254250
}
@@ -261,6 +257,7 @@ public static function error($text)
261257
public static function debug($text)
262258
{
263259
if (self::isDebugLogActive()) {
260+
$text = self::getLogText($text, func_get_args());
264261
self::$monolog->debug($text);
265262
}
266263
}
@@ -273,7 +270,25 @@ public static function debug($text)
273270
public static function update($text)
274271
{
275272
if (self::isUpdateLogActive()) {
273+
$text = self::getLogText($text, func_get_args());
276274
self::$monolog_update->info($text);
277275
}
278276
}
277+
278+
/**
279+
* Applies vsprintf to the text if placeholder replacements are passed along.
280+
*
281+
* @param string $text
282+
* @param array $args
283+
*
284+
* @return string
285+
*/
286+
protected static function getLogText($text, array $args = [])
287+
{
288+
// Pop the $text off the array, as it gets passed via func_get_args().
289+
array_shift($args);
290+
291+
// Suppress warning if placeholders don't match out.
292+
return @vsprintf($text, $args) ?: $text;
293+
}
279294
}

tests/unit/TelegramLogTest.php

+22-9
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class TelegramLogTest extends TestCase
2626
/**
2727
* @var array Dummy logfile paths
2828
*/
29-
private $logfiles = [
29+
private static $logfiles = [
3030
'error' => '/tmp/php-telegram-bot-errorlog.log',
3131
'debug' => '/tmp/php-telegram-bot-debuglog.log',
3232
'update' => '/tmp/php-telegram-bot-updatelog.log',
@@ -48,7 +48,7 @@ protected function setUp()
4848
protected function tearDown()
4949
{
5050
// Make sure no logfiles exist.
51-
foreach ($this->logfiles as $file) {
51+
foreach (self::$logfiles as $file) {
5252
file_exists($file) && unlink($file);
5353
}
5454
}
@@ -79,37 +79,46 @@ public function testNewInstanceWithoutUpdatePath()
7979

8080
public function testErrorStream()
8181
{
82-
$file = $this->logfiles['error'];
82+
$file = self::$logfiles['error'];
8383
$this->assertFileNotExists($file);
8484
TelegramLog::initErrorLog($file);
8585
TelegramLog::error('my error');
86+
TelegramLog::error('my %s error', 'placeholder');
8687
$this->assertFileExists($file);
87-
$this->assertContains('bot_log.ERROR: my error', file_get_contents($file));
88+
$error_log = file_get_contents($file);
89+
$this->assertContains('bot_log.ERROR: my error', $error_log);
90+
$this->assertContains('bot_log.ERROR: my placeholder error', $error_log);
8891
}
8992

9093
public function testDebugStream()
9194
{
92-
$file = $this->logfiles['debug'];
95+
$file = self::$logfiles['debug'];
9396
$this->assertFileNotExists($file);
9497
TelegramLog::initDebugLog($file);
9598
TelegramLog::debug('my debug');
99+
TelegramLog::debug('my %s debug', 'placeholder');
96100
$this->assertFileExists($file);
97-
$this->assertContains('bot_log.DEBUG: my debug', file_get_contents($file));
101+
$debug_log = file_get_contents($file);
102+
$this->assertContains('bot_log.DEBUG: my debug', $debug_log);
103+
$this->assertContains('bot_log.DEBUG: my placeholder debug', $debug_log);
98104
}
99105

100106
public function testUpdateStream()
101107
{
102-
$file = $this->logfiles['update'];
108+
$file = self::$logfiles['update'];
103109
$this->assertFileNotExists($file);
104110
TelegramLog::initUpdateLog($file);
105111
TelegramLog::update('my update');
112+
TelegramLog::update('my %s update', 'placeholder');
106113
$this->assertFileExists($file);
107-
$this->assertContains('my update', file_get_contents($file));
114+
$debug_log = file_get_contents($file);
115+
$this->assertContains('my update', $debug_log);
116+
$this->assertContains('my placeholder update', $debug_log);
108117
}
109118

110119
public function testExternalStream()
111120
{
112-
$file = $this->logfiles['external'];
121+
$file = self::$logfiles['external'];
113122
$this->assertFileNotExists($file);
114123

115124
$external_monolog = new Logger('bot_update_log');
@@ -118,11 +127,15 @@ public function testExternalStream()
118127

119128
TelegramLog::initialize($external_monolog);
120129
TelegramLog::error('my error');
130+
TelegramLog::error('my %s error', 'placeholder');
121131
TelegramLog::debug('my debug');
132+
TelegramLog::debug('my %s debug', 'placeholder');
122133

123134
$this->assertFileExists($file);
124135
$file_contents = file_get_contents($file);
125136
$this->assertContains('bot_update_log.ERROR: my error', $file_contents);
137+
$this->assertContains('bot_update_log.ERROR: my placeholder error', $file_contents);
126138
$this->assertContains('bot_update_log.DEBUG: my debug', $file_contents);
139+
$this->assertContains('bot_update_log.DEBUG: my placeholder debug', $file_contents);
127140
}
128141
}

0 commit comments

Comments
 (0)