Skip to content

Commit 609a2d6

Browse files
committed
[Add] Add printerLogger to PerformancePrinter
1 parent 5c2c25c commit 609a2d6

File tree

4 files changed

+241
-20
lines changed

4 files changed

+241
-20
lines changed

README.md

+14-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<p align="center">
44
<a link="https://packagist.org/packages/tsaikoga/performance-printer" style="text-decoration:none;">
5-
<img src="https://img.shields.io/badge/stable-v1.0.1-brightgreen" alt="Unstable">
5+
<img src="https://img.shields.io/badge/stable-v1.1.1-brightgreen" alt="Unstable">
66
</a>
77
<a link="https://packagist.org/packages/tsaikoga/performance-printer" style="text-decoration:none;">
88
<img src="https://img.shields.io/badge/unstable-dev--master-blue" alt="Unstable">
@@ -36,11 +36,13 @@ Performance Printer is a laravel package to print each requests' performance inf
3636
3737
## Usage
3838
1. Install the package for development environment:
39-
Stable version:
39+
40+
**Stable version**:
4041
```bash
4142
composer require tsaikoga/performance-printer --dev
4243
```
43-
Unstable version:
44+
45+
**Unstable version**:
4446
```bash
4547
composer require tsaikoga/performance-printer:dev-master --dev
4648
```
@@ -82,6 +84,15 @@ return [
8284

8385
// enable this package or disable it
8486
'enable' => true,
87+
88+
// log
89+
'log' => [
90+
// is logging enable?
91+
'enable' => true,
92+
93+
// The path that the log file stored
94+
'filepath' => '/tmp/performance_printer.log',
95+
],
8596
];
8697
```
8798

src/Printer/Printer.php

+69-17
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
/**
33
* @package PerformancePrinter
44
* @author TsaiKoga
5-
* @version 1.0.0
5+
* @version 1.1.1
66
*
77
*/
88
namespace TsaiKoga\PerformancePrinter\Printer;
99

1010
use Symfony\Component\Console\Helper\Table;
1111
use Symfony\Component\Console\Style\SymfonyStyle;
1212
use Symfony\Component\Console\Output\ConsoleOutput;
13+
use TsaiKoga\PerformancePrinter\Printer\PrinterLogger;
1314

1415
class Printer extends ConsoleOutput
1516
{
@@ -56,6 +57,21 @@ class Printer extends ConsoleOutput
5657
*/
5758
protected $lang;
5859

60+
61+
/**
62+
* is logging enabled
63+
*
64+
* @var bool
65+
*/
66+
protected $is_logging_enabled;
67+
68+
/**
69+
* logger
70+
*
71+
* @var \Monolog\Logger
72+
*/
73+
protected $logger;
74+
5975
/**
6076
* Create a new Printer instance.
6177
*
@@ -112,6 +128,22 @@ public function setLang($lang = 'en')
112128
return $this;
113129
}
114130

131+
/**
132+
* Enable logging
133+
*
134+
* @param string $filepath
135+
* @return TsaiKoga\PerformancePrinter\Printer\Printer $this
136+
*/
137+
public function enableLogging($filepath)
138+
{
139+
$this->is_logging_enabled = true;
140+
$logger = new PrinterLogger();
141+
$logger->pushHandler($logger->setFormatter($filepath));
142+
$this->logger = $logger;
143+
return $this;
144+
145+
}
146+
115147
/**
116148
* Get table
117149
*
@@ -147,6 +179,10 @@ protected function outputTable($table, $header, $content)
147179
$table->setRows($content);
148180
$table->render();
149181
}
182+
183+
if ($this->is_logging_enabled) {
184+
$this->logger->renderTable($header, $content);
185+
}
150186
}
151187

152188
/**
@@ -157,10 +193,10 @@ protected function outputTable($table, $header, $content)
157193
public function outputRequest()
158194
{
159195
$request = $this->request->server();
160-
$this->writeln("<question>[ {$request['REQUEST_METHOD']} ]</question> <info>{$request['REQUEST_URI']}</info>");
196+
$this->outputMsg("<question>[ {$request['REQUEST_METHOD']} ]</question> <info>{$request['REQUEST_URI']}</info>");
161197
if (in_array($request['REQUEST_METHOD'], ['POST', 'PUT', 'PATCH'])) {
162-
if (isset($request['HTTP_CONTENT_TYPE'])) $this->writeln("<question>[ Content-Type ]</question> : {$request['HTTP_CONTENT_TYPE']} ");
163-
$this->writeln($this->request->getContent());
198+
if (isset($request['HTTP_CONTENT_TYPE'])) $this->outputMsg("<question>[ Content-Type ]</question> : {$request['HTTP_CONTENT_TYPE']} ");
199+
$this->outputMsg($this->request->getContent());
164200
}
165201
}
166202

@@ -173,9 +209,9 @@ public function outputFilesCount()
173209
{
174210
$included_files_count = count(get_included_files());
175211
if ($this->lang === 'en') {
176-
$this->writeln("<question>[ Included Files Count ] </question> $included_files_count");
212+
$this->outputMsg("<question>[ Included Files Count ] </question> $included_files_count");
177213
} else {
178-
$this->writeln("<question>[ 加载文件数量 ] </question> $included_files_count");
214+
$this->outputMsg("<question>[ 加载文件数量 ] </question> $included_files_count");
179215
}
180216
}
181217

@@ -189,9 +225,9 @@ public function outputQueryCount()
189225
$total = $this->querylog->getQueriesTotal();
190226
$times = $this->querylog->getQueriesRunningTime();
191227
if ($this->lang === 'en') {
192-
$this->writeln("<question>[ Total ]</question> $total queries and ran for $times ms.");
228+
$this->outputMsg("<question>[ Total ]</question> $total queries and ran for $times ms.");
193229
} else {
194-
$this->writeln("<question>[ 总计 ]</question> $total 条语句运行了 $times 毫秒。");
230+
$this->outputMsg("<question>[ 总计 ]</question> $total 条语句运行了 $times 毫秒。");
195231
}
196232
}
197233

@@ -217,17 +253,17 @@ protected function outputRawSql($log)
217253
{
218254
if ($this->lang === 'en') {
219255
if ($log['count'] > 1) {
220-
$this->writeln("<info>>>>></info> There are a total of {$log['count']} same queries with different bindings:");
221-
$this->writeln("<question>[ These queries ran for {$log['time']} ms totally ]</question> RAW SQL: <info>{$log['sql']}</info>");
256+
$this->outputMsg("<info>>>>></info> There are a total of {$log['count']} same queries with different bindings:");
257+
$this->outputMsg("<question>[ These queries ran for {$log['time']} ms totally ]</question> RAW SQL: <info>{$log['sql']}</info>");
222258
} else {
223-
$this->writeln("<question>[ SQL ran for {$log['time']} ms ]</question> RAW SQL: <info>{$log['sql']}</info>");
259+
$this->outputMsg("<question>[ SQL ran for {$log['time']} ms ]</question> RAW SQL: <info>{$log['sql']}</info>");
224260
}
225261
} else {
226262
if ($log['count'] > 1) {
227-
$this->writeln("<info>>>>></info> 总共有 {$log['count']} 条相同的查询只是查询参数不同:");
228-
$this->writeln("<question>[ 这些查询总共运行 {$log['time']} 毫秒 ]</question> 原生 SQL: <info>{$log['sql']}</info>");
263+
$this->outputMsg("<info>>>>></info> 总共有 {$log['count']} 条相同的查询只是查询参数不同:");
264+
$this->outputMsg("<question>[ 这些查询总共运行 {$log['time']} 毫秒 ]</question> 原生 SQL: <info>{$log['sql']}</info>");
229265
} else {
230-
$this->writeln("<question>[ SQL 运行了 {$log['time']} 毫秒 ]</question> 原生 SQL: <info>{$log['sql']}</info>");
266+
$this->outputMsg("<question>[ SQL 运行了 {$log['time']} 毫秒 ]</question> 原生 SQL: <info>{$log['sql']}</info>");
231267
}
232268
}
233269

@@ -254,9 +290,9 @@ public function outputResponse()
254290
{
255291
$response = $this->response->content();
256292
if ($this->lang === 'en') {
257-
$this->writeln("<question>[ Response Load $this->expense ms]</question> $response");
293+
$this->outputMsg("<question>[ Response Load $this->expense ms]</question> $response");
258294
} else {
259-
$this->writeln("<question>[ 响应时间 $this->expense 毫秒 ]</question> $response");
295+
$this->outputMsg("<question>[ 响应时间 $this->expense 毫秒 ]</question> $response");
260296
}
261297
}
262298

@@ -270,6 +306,23 @@ public function outputBlankLine($num)
270306
{
271307
foreach(range(1, $num) as $i) {
272308
$this->writeln('');
309+
if ($this->is_logging_enabled) {
310+
$this->logger->info('');
311+
}
312+
}
313+
}
314+
315+
/**
316+
* output message
317+
*
318+
* @param string $msg
319+
* @return void
320+
*/
321+
public function outputMsg($msg)
322+
{
323+
$this->writeln($msg);
324+
if ($this->is_logging_enabled) {
325+
$this->logger->info(strip_tags($msg));
273326
}
274327
}
275328

@@ -285,5 +338,4 @@ public function outputBlankLine($num)
285338
protected function outputIndexSuggestion($sql, $query, $bindings, $explains)
286339
{
287340
}
288-
289341
}

src/Printer/PrinterLogger.php

+155
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
<?php
2+
/**
3+
* @package PerformancePrinter
4+
* @author TsaiKoga
5+
* @version 1.1.1
6+
*
7+
*/
8+
namespace TsaiKoga\PerformancePrinter\Printer;
9+
10+
use Monolog\Logger;
11+
use Monolog\Formatter\LineFormatter;
12+
use Monolog\Handler\StreamHandler;
13+
14+
class PrinterLogger extends Logger
15+
{
16+
17+
/**
18+
* Create a new command instance.
19+
*
20+
* @param string $logger_name
21+
*/
22+
public function __construct($logger_name="PrinterPerformance")
23+
{
24+
parent::__construct($logger_name);
25+
}
26+
27+
/**
28+
* Set formatter to Logger
29+
*
30+
* @param string $filepath
31+
* @return Monolog\Handler\StreamHandler $debug_handler
32+
*/
33+
public function setFormatter($filepath)
34+
{
35+
$formatter = new LineFormatter(
36+
"%message% %context% %extra%\n", // Format of message in log
37+
null, // Datetime format
38+
true, // allowInlineLineBreaks option, default false
39+
true // ignoreEmptyContextAndExtra option, default false
40+
);
41+
$debug_handler = new StreamHandler($filepath, Logger::DEBUG);
42+
$debug_handler->setFormatter($formatter);
43+
return $debug_handler;
44+
}
45+
46+
/**
47+
* build table array for rendering
48+
*
49+
* @param array $header
50+
* @param array $content
51+
* @return array
52+
*/
53+
public function buildTable($header, $content)
54+
{
55+
$cols_count = count($header);
56+
$rows_count = count($content);
57+
$data = array_merge([$header], $content);
58+
$space_count = 2;
59+
60+
$result = array();
61+
$max_len = $this->getMaxLenOfRows($cols_count, $rows_count, $data);
62+
63+
foreach (range(0, $rows_count) as $rows_index) {
64+
// For header
65+
if ($rows_index === 0) {
66+
foreach ($data[$rows_index] as $i => $item) {
67+
$index = $rows_index;
68+
$strlen = strlen($item);
69+
// concat string and convert it to something like this: +-------+
70+
if ($i === 0){
71+
$result[$index][$i] = '+' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
72+
$index += 1;
73+
$space_suffix = str_repeat(' ', ($max_len[$i] - $strlen));
74+
$result[$index][$i] = '| ' . $item . $space_suffix . ' |';
75+
$index += 1;
76+
$result[$index][$i] = '+' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
77+
$index += 1;
78+
} else {
79+
$result[$index][$i] = '' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
80+
$index += 1;
81+
$space_suffix = str_repeat(' ', ($max_len[$i] - $strlen));
82+
$result[$index][$i] = ' ' . $item . $space_suffix . ' |';
83+
$index += 1;
84+
$result[$index][$i] = '' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
85+
$index += 1;
86+
}
87+
}
88+
} else {
89+
// Add For Content
90+
foreach ($data[$rows_index] as $i => $item) {
91+
$index = $rows_index + 3;
92+
$strlen = strlen($item);
93+
if ($i === 0) {
94+
$space_suffix = str_repeat(' ', ($max_len[$i] - $strlen));
95+
$result[$index][$i] = '| ' . $item . $space_suffix . ' |';
96+
$index += 1;
97+
} else {
98+
$space_suffix = str_repeat(' ', ($max_len[$i] - $strlen));
99+
$result[$index][$i] = ' ' . $item . $space_suffix . ' |';
100+
$index += 1;
101+
}
102+
}
103+
}
104+
105+
// Add bottom line
106+
if ($rows_index >= $rows_count) {
107+
foreach ($data[$rows_index] as $i => $item) {
108+
if ($i === 1) {
109+
$result[$index][$i] = '+' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
110+
} else {
111+
$result[$index][$i] = '' . str_repeat('-', ($max_len[$i] + $space_count)) . '+';
112+
}
113+
}
114+
}
115+
}
116+
return $result;
117+
}
118+
119+
/**
120+
* Get max length of each field's value
121+
*
122+
* @param integer $cols_count
123+
* @param integer $rows_count
124+
* @param array $data
125+
* @return array
126+
*/
127+
public function getMaxLenOfRows($cols_count, $rows_count, $data)
128+
{
129+
$length = array();
130+
foreach (range(0, $cols_count - 1) as $col_index) {
131+
$max_len = 0;
132+
foreach(range(0, $rows_count) as $row_index) {
133+
$str_len = strlen($data[$row_index][$col_index]);
134+
if ($max_len <= $str_len) $max_len = $str_len;
135+
}
136+
$length[$col_index] = $max_len;
137+
}
138+
return $length;
139+
}
140+
141+
/**
142+
* render table
143+
*
144+
* @param array $header
145+
* @param array $content
146+
* @return void
147+
*/
148+
public function renderTable($header, $content)
149+
{
150+
$result = $this->buildTable($header, $content);
151+
foreach ($result as $i => $items) {
152+
$this->info(implode('', $items));
153+
}
154+
}
155+
}

src/Printer/PrinterManager.php

+3
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ public function print($event)
4848
$printer = new Printer($event->request, $event->response, $querylog);
4949
$printer->setTableStyle($this->options['table_style']);
5050
$printer->setLang($this->options['lang']);
51+
if ($this->options['log']['enable']) {
52+
$printer->enableLogging($this->options['log']['filepath']);
53+
}
5154

5255
if ($this->options['request']) {
5356
$printer->outputRequest();

0 commit comments

Comments
 (0)