So I am trying to make a method that allows for logging debug messages on the fly, and I would like to include the file name and line number where the message occured. My first inclination was to give debug_backtrace() as one of the arguments for the logging method, which returns an array which contains the current file name and line number.
The problem is, this only gives the file and line of the very first file called (index.php). index.php is only a five line file that calls a method from a class in an included file however, so the line and file information always say (index.php, line 5) no matter what and are useless.
Is there a way to get the current line and file no matter where in the code you are?
Addition
Here is the file and line info:
[2011-01-23 06:26:10] Information: "Request made for non-existant controller (test).", File: "/home/spotless/public_html/mymvc/index.php", Line: 5, Request: "/test"
Here is the index.php in its entirety:
<?php
include_once('application/init.php');
lev_init::init();
?>
Here is the logging call using the debug_backtrace(), within the init.php file (line 37):
// if requested controller does not exist, log
lev_logging::message('Request made for non-existant controller ('.$requested_controller.').', debug_backtrace());
second update
var_dump of debug_backtrace
array(1) { [0]=> array(6) { ["file"]=> string(42) "/home/spotless/开发者_JS百科public_html/mymvc/index.php" ["line"]=> int(5) ["function"]=> string(4) "init" ["class"]=> string(8) "lev_init" ["type"]=> string(2) "::" ["args"]=> array(0) { } } }
If you are in the global context with this, not a function, then what you show is normal behaviour. The inclusion of files does not reflect in the call stack - only the calling of functions and methods.
As far as I know, there is no way to build an "include trace", a list of the nested includes a line of code is in. This has been asked repeatedly on SO, and IIRC, a solution was never found.
debug_backtrace
returns an array so do a var_export(debug_backtrace(), true)
i.e.:
// if requested controller does not exist, log
lev_logging::message('Request made for non-existant controller ('.$requested_controller.').', var_export(debug_backtrace(), true));
Note:
just and edit what what/where the stack trace matters.
<?php
// filename: /tmp/a.php
function b_test($foo)
{
var_dump(debug_backtrace());
}
function a_test($str)
{
echo "\nHi: $str";
b_test('bar');
var_dump(debug_backtrace());
}
a_test('friend');
?>
<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>
The debug_backtrace in b_test will show everything up to the include. the one in a_test won't show the b_test call since it has returned...
精彩评论