1
|
|
|
<?php |
2
|
|
|
namespace Logger; |
3
|
|
|
|
4
|
|
|
use Exception; |
5
|
|
|
|
6
|
|
|
class StackTracePrinter { |
7
|
|
|
/** |
8
|
|
|
* @param Exception $e |
9
|
|
|
* @param string $messageIntro |
10
|
|
|
*/ |
11
|
|
|
public static function printException(Exception $e, $messageIntro = '') { |
12
|
|
|
self::p("%s[%s] %s\n", $messageIntro, get_class($e), $e->getMessage()); |
13
|
|
|
|
14
|
|
|
foreach($e->getTrace() as $idx => $station) { |
15
|
|
|
self::formatStation($idx, $station); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
if($e->getPrevious() instanceof Exception) { |
19
|
|
|
self::p(); |
20
|
|
|
self::printException($e->getPrevious(), 'Previous: '); |
21
|
|
|
} |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param int $idx |
26
|
|
|
* @param array $station |
27
|
|
|
*/ |
28
|
|
|
private static function formatStation($idx, $station) { |
29
|
|
|
$defaults = array( |
30
|
|
|
'file' => null, |
31
|
|
|
'line' => null, |
32
|
|
|
'class' => null, |
33
|
|
|
'function' => null, |
34
|
|
|
'type' => null, |
35
|
|
|
'args' => array(), |
36
|
|
|
); |
37
|
|
|
$station = array_merge($defaults, $station); |
38
|
|
|
self::p("#%- 3s%s:%d\n", $idx, $station['file'] ?: 'unknown', $station['line']); |
39
|
|
|
if($station['class'] !== null || $station['function'] !== null) { |
40
|
|
|
$params = array(); |
41
|
|
|
foreach(is_array($station['args']) ? $station['args'] : array() as $argument) { |
42
|
|
|
if(is_array($argument)) { |
43
|
|
|
$params[] = sprintf('array%d', count($argument)); |
44
|
|
|
} elseif(is_object($argument)) { |
45
|
|
|
$params[] = sprintf('%s', get_class($argument)); |
46
|
|
|
} else { |
47
|
|
|
$params[] = gettype($argument); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
if(strpos($station['function'], '{closure}') !== false && $station['class'] !== null) { |
51
|
|
|
$station['function'] = '{closure}'; |
52
|
|
|
} |
53
|
|
|
self::p(" %s%s%s%s%s%s\n", $station['class'], $station['type'], $station['function'], "(", join(', ', $params), ")"); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param string $format |
59
|
|
|
*/ |
60
|
|
|
private static function p($format = "\n") { |
61
|
|
|
$fp = fopen('php://stderr', 'w'); |
62
|
|
|
fwrite($fp, vsprintf($format, array_slice(func_get_args(), 1))); |
63
|
|
|
fclose($fp); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|