-
Notifications
You must be signed in to change notification settings - Fork 0
/
ccTrace.php
469 lines (440 loc) · 14.7 KB
/
ccTrace.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php
/**
* This is an example (and default case) for a class that performs logging. It
* is attached to, but loosely coupled from the ccApp class.
*
* @see http://logging.apache.org/log4php/docs
* @see http://codefury.net/projects/klogger/
*
* @package ccPhp
*/
//!namespace ccPhp\core;
list ($bb, $eb, $bi, $ei, $btt, $ett, $rarr, $ldquo, $rdquo, $hellip, $nbsp, $nl, $bred, $ered) =
array('<b>','</b>','<i>','</i>','<tt>','</tt>','→','“','”','…',' ','<br/>'.PHP_EOL,'<font color="red">','</font>');
/*
interface ccDebugSourceInterface // Class supports developer
{ // support functions
function getCaller($depth, $path); // Get caller label
function showSource($file,$line=0,$context=-1); // Display PHP sourcefile
function showStack(Array $traceback=NULL); // Renamed from showTrace()
} // interface ccDebugSourceInterface
interface ccTraceInterface // Class implements trace output
{
function setOutput($path=NULL); // bool|string ON|OFF|destination
// function setHtml($bEnable=TRUE); // Enale/disable HTML formatting
// function setSuppress($bSuppress=TRUE); // Suppress output
function tr(...); // Trace output
function out($string); // Unbuffered output
} // interface ccTraceInterface
interface ccLoggerInterface // Class implements log output
{
function setLogging($path); // bool|string ON|OFF|destination
function log(...); // Log output
function out($string); // Unbuffered output
} // interface ccLoggerInterface
*/
/**
* Trace output class.
* @package ccPhp
*/
class ccTrace
// implements ccTraceInterface, ccLoggerInterface, ccDebugSourceInterface
{
protected $DefaultLevel = 9;// Default output level of detail
protected $ThresholdLevel=5;
static protected $bHtml=TRUE; // Format for HTML?
static protected $Output=NULL; // Destination
static protected $bSuppress=FALSE; // Suppress output?
static protected $log=TRUE; // bool|string
/**
* Turn on/off HTML formatting. On is useful if the output is to appear
* on the web page; not so useful when output to a terminal console or
* file. It also sets a class variable (i.e., static), $bHttml, to signal
* output methods for special output handling.
*
* @param boolean $bEnable Enable or disable HTML output.
*/
static function setHtml($bEnable=TRUE)
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$bred,$ered,$nl;
self::$bHtml = $bEnable;
if ($bEnable)
{
list ($bb, $eb, $bi, $ei, $btt, $ett, $rarr, $ldquo, $rdquo, $hellip, $nbsp, $nl, $bred, $ered) =
array('<b>','</b>','<i>','</i>','<tt>','</tt>','→','“','”','…',' ','<br/>'.PHP_EOL,'<font color="red">','</font>'.PHP_EOL);
}
else
{
$bb = $eb =
$bi = $ei =
$btt = $ett =
$bred = $ered = '';
list ($rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl) =
array('->', '"', '"', '...', ' ', PHP_EOL);
}
} // setHtml()
/**
* Turns logging output on/off and can define an output file to output to.
* @param bool|string $log bool: enable|disable; string: output name
* @see self::log()
*/
static function setLogging($log=TRUE)
{
self::$log = $log;
if (is_string($log))
{
ini_set('error_log',$log);
}
else
ini_set('error_log',NULL);
} // setLogging()
/**
* Specifies that a file should be used for output. If set, HTML formatting
* is automatically disabled (since it rarely makes sense to format for
* HTML) in a text file. If HTML output is definitely wanted, setHtml() can
* be explictly called after this method.
* @param string $filepath Name of the output file (or NULL);
*/
static function setOutput($filepath=NULL)
{
self::$Output = $filepath;
self::setHtml(!self::$Output);
}
/**
* Force suppression of any output via the output methods in this class.
* It is a draconean way to make sure no junk appears in the output and
* might only be useful for production releases.
* @param boolean $bSuppress [description]
*/
static function setSuppress($bSuppress=TRUE)
{
self::$bSuppress=$bSuppress;
}
/**
* Output string to log file, if defined. If a log file is not defined, output
* is displayed in stdout. When displayed, it is influenced by the bHtml setting.
* Unlike s_out() this output is not affected by the setSuppress() setting.
* @param string $msg
* @param bool $noNewLine If msg is displayed, the newline can be suppressed
*/
function out($msg, $bNoNewline=FALSE)
{
if ($this->Output)
error_log($msg,3,$this->Output);
else {
$this->bHtml && $msg = nl2br($msg);
if (!$bNoNewline) {
$this->bHtml && $msg .= '<br/>';
echo $msg.PHP_EOL;
}
else
echo $msg;
}
/* if ($bNoNewline)
{
if ($this->bHtml)
echo nl2br($msg);
else
echo $msg;
}
else
{
if ($this->bHtml)
echo nl2br($msg).'<br/>'.PHP_EOL;
else
echo $msg.PHP_EOL;
}
*/ } // out()
/**
* Format a line of the trace stack.
* @param array $line Content reprsenting a stack frame.
*
* @see debug_traceback() http://us.php.net/manual/en/function.debug-backtrace.php
* @see Exception::getTrace() http://us.php.net/manual/en/exception.gettrace.php
* @todo Consider moving to separate Trace class
*/
static function fmtTraceLine($line)
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl;
$out = '';
if (isset($line['class']))
$out .= $bb.$line['class'].$eb;
if (isset($line['object'])
&& get_class($line['object']) != $line['class'])
$out .= $bi.'('.get_class($line['object']).')'.$ei;
if (isset($line['type']))
$out .= ($line['type'] == '->' ? $rarr : $line['type']);
$out .= $bb.$line['function'].$eb.'(';
$first = true;
if (isset($line['args']))
foreach ($line['args'] as $arg)
{
if (!$first)
$out .= ',';
else
$first = false;
$out .= $btt;
if ($arg === NULL)
$out .= 'null';
elseif (is_object($arg))
$out .= get_class($arg);
elseif (is_string($arg))
if (self::$bHtml)
$out .= $ett.$ldquo.$bi.htmlentities($arg).$ei.$rdquo.$btt;
else
$out .= $ett.$ldquo.$bi.$arg.$ei.$rdquo.$btt;
elseif (is_array($arg))
{
if (( $line['function'] == 'call_user_func'
|| $line['function'] == 'call_user_func_array')
&& count($arg) == 2)
{
$out .= get_class($arg[0]);
if (is_object($arg[0]))
$out .= $rarr;
else
$out .= '::';
$out .= $arg[1].'()'.$ett.','.$hellip;
break;
}
else
{
$out .= 'Array(';
$firstarg = true;
foreach ($arg as $argkey => $argval)
{
if (!$firstarg)
$out .= ',';
else
$firstarg = false;
$out .= $argkey.$rarr;
if ($argval === NULL)
$out .= 'null';
elseif (is_object($argval))
$out .= get_class($argval);
elseif (is_string($argval))
if (self::$bHtml)
$out .= $ett.$ldquo.$bi.htmlentities($argval).$ei.$rdquo.$btt;
else
$out .= $ett.$ldquo.$bi.$argval.$ei.$rdquo.$btt;
else
$out .= $argval;
}
$out .= ')';
}
}
else
$out .= $arg;
$out .= $ett;
}
$out .= ')';
if (isset($line['file']))
$out .= ' in '.self::fmtPath($line['file'],$line['line']);
// $out .= ' in '.$btt.dirname($line['file']).'/'.$ett.$bb.basename($line['file']).$eb.'#'.$line['line'];
// var_dump($line['args']);
// echo ' '.implode(',',$line['args']).'<br/>';
return $out;
} // fmtTraceLine()
/**
* Format filepath for output. For HTML output, this will highlight the filename
* part of the path and suffix a line number.
* (e.g., '/root/part1/.../filename.ext[#line]')
* @return string Formatted path name
*/
static function fmtPath($path, $line=NULL)
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl;
$dirname = dirname($path);
$dirname === '.' && $dirname = '';
if ($dirname)
$dirname = $btt.$dirname.DIRECTORY_SEPARATOR.$ett;
return $dirname.$bb.basename($path).$eb. ($line ? '#'.$line : '');
}
/**
* Return formated phrase of caller.
* @param int $traceOffset How far back in the callback stack to look.
* @param string $path Matching root path to display (ignore stack entries
* that do not match in order to show only "app" sources).
*
* @return string Caller [filename][ [class{::|->}[{function}()][#{line#}]
*/
static function getCaller($traceOffset = 1, $path=NULL)
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl;
if (PHP_VERSION_ID >= 50400)
$trace = debug_backtrace(
DEBUG_BACKTRACE_IGNORE_ARGS
|DEBUG_BACKTRACE_PROVIDE_OBJECT
,$traceOffset+1);
elseif (PHP_VERSION_ID >= 50306)
$trace = debug_backtrace(
DEBUG_BACKTRACE_IGNORE_ARGS
|DEBUG_BACKTRACE_PROVIDE_OBJECT
);
else
$trace = debug_backtrace(TRUE);
// $debug_caller = FALSE;
$out = '';
if ($path && file_exists($path)) // Search first file in app
{
// if ($debug_caller) $out .= '#'.__LINE__.' '.$path.' ';
if (substr($path,-1) != DIRECTORY_SEPARATOR)
$path .= DIRECTORY_SEPARATOR;
// for ($traceOffset=$traceOffset+1;$traceOffset;$traceOffset--)
// array_shift($trace); // Ignore 1st entries & reset offset
// Ignore 1st entries & search for entries that start w/path
for ($traceOffset;
isset($trace[$traceOffset])
&& (!isset($trace[$traceOffset]['file'])
|| strpos($trace[$traceOffset]['file'],$path) !== 0);
$traceOffset++);
}
elseif (!isset($trace[$traceOffset]['file']))
$traceOffset += 2; // If no location, caller was invoked indirectly, so skip indirection call
$file = $trace[$traceOffset]['file'];
$line = $trace[$traceOffset]['line'];
$traceOffset++; // Get name of function that included
if (isset($trace[$traceOffset]['class'])) // Set class info, if exists
{
// if ($debug_caller) $out .= '#'.__LINE__.' ';
$out .= $bb.$trace[$traceOffset]['class'].$eb;
if (isset($trace[$traceOffset]['object'])
&& get_class($trace[$traceOffset]['object']) != $trace[$traceOffset]['class'])
$out .= $bi.'('.get_class($trace[$traceOffset]['object']).')'.$ei;
if (isset($trace[$traceOffset]['type']))
$out .= ($trace[$traceOffset]['type'] == '->' ? $rarr : $trace[$traceOffset]['type']);
}
if (isset($trace[$traceOffset]['function'])
&& !( $trace[$traceOffset]['function'] === 'include'
|| $trace[$traceOffset]['function'] === 'include_once'
|| $trace[$traceOffset]['function'] === 'require'
|| $trace[$traceOffset]['function'] === 'require_once'
)
)
$out .= $bb.$trace[$traceOffset]['function'].$eb.'()'
. '#'.$line;
else // If no acceptable function name, show path
$out .= self::fmtPath($file,$line);
return $out;
} // getCaller()
/**
* Display PHP source content from a file with line nuumbers.
* @param string $file File to display.
* @param int $line File line number to highlight
*/
static function showSource($file,$line=NULL)
{
echo <<<EOD
<a href="#currentline">{$file}#$line<a><br/>
<style type="text/css">
.num {
float: left;
color: gray;
text-align: right;
margin-right: 3pt;
padding-right: 3pt;
border-right: 1px solid gray;}
</style>
EOD;
$linenos = range(1, count(file($file)));
$linenos[$line-1] = '<b id="currentline" style="color:white; background:red">' . $linenos[$line-1] . '</b>';
echo '<code class="num">', implode('<br/>',$linenos), '</code>';
highlight_file($file);
/*
echo $file.'#'.$line.'<br/>';
if ($line === NULL)
highlight_file($file);
else
{
$source = highlight_file($file, TRUE);
$source= explode('<br />', $source);
$width = strlen(count($source));
foreach ($source as $lineno => $sline)
$source[$lineno] = '<code style="padding-right:3px;margin-right:3px; color:black; border-right:1px solid gray;">'.str_replace(' ',' ',str_pad(($lineno+1), $width)).'</code>'.$sline;
$source[$line-1] = '<b id="currentline" style="width:100%; background:rgb(200,200,200)">'.$source[$line-1].'</b>';
print_r(implode('<br/>',$source));
}
*/
} // showSource()
/**
* Display traceback call-stack.
* @param Array $trace is the trace-back array as generated by
* debug_backtrace() and Exception::getTrace(). If not specified,
* debug_backtrace() is used.
* @todo Consider moving to separate Trace class
*/
static function showTrace(Array $trace=NULL)
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl;
$trace === NULL && $trace=debug_backtrace();
$entry = 1;
foreach ($trace as $key => $line)
{
if (isset($line['file']) && isset($line['line']))
{
self::s_out( ($entry++).'. '.self::fmtTraceLine($line).$nl);
if ( $line['function'] == 'call_user_func'
|| $line['function'] == 'call_user_func_array')
{
self::s_out( $nbsp.$nbsp.$nbsp.$nbsp.self::fmtTraceLine($trace[$key-1]).$nl);
}
}
}
// self::showSource($trace[0]['file'],$trace[0]['line']);
// echo '</pre>';
} // showTrace()
/**
* Output content to the log file, prefixed with time/date.
* @param string $string Text to output
* @todo Consider decorating output with timestamp, IP, etc.
*/
static function log($string='')
{
if (is_string(self::$log)) // If output filename had been set,
error_log($string); // output to log file.
elseif (self::$log) // If no output destination
self::s_out($string.PHP_EOL); // Just send it to the default place
} // log()
/**
* Suppressable output.
* Output text to stdout or a file (depending on settings). EOL breaks
* are not assumed—new line or <br> need to be included, if desired.
* @param string $string Text to output.
*/
static function s_out($string)
{
if (self::$bSuppress)
return;
// echo __METHOD__.__LINE__.' '.self::$Output.'<br/>';
if (self::$Output)
error_log($string,3,self::$Output);
else
echo $string;
} // s_out()
/**
* Output content prefixed with the source line, file, method, class it is
* called from. If the content is not a string, it is interpreted by print_r().
*
* options: HTML, log, stderr, stdout, formatted, timestamp
* @param mixed $msg Item to output.
*/
static function tr($msg='')
{
global $bb,$eb, $bi,$ei, $btt,$ett, $rarr,$ldquo,$rdquo,$hellip,$nbsp,$nl;
// echo '<pre>';
// debug_print_backtrace();
// echo '</pre>';
$out = self::getCaller(1); // Get formatted source-code line decoration
if ($msg === '' || $msg === NULL || is_string($msg))
self::s_out($out.' '.$msg.$nl);
else
{
if (self::$bHtml) self::s_out('<span style="display:run-in;">');
self::s_out($out.' ');
if (self::$bHtml) self::s_out('</span><pre>');
self::s_out(print_r($msg,TRUE));
self::s_out(PHP_EOL);
if (self::$bHtml) self::s_out('</pre>');
}
} // tr()
} // class ccTrace