views:

47

answers:

3

Well, I don't know if thats what I want. But here is my problem:

In case of some error I am logging the FILE, CLASS, FUNCTION and LINE in a file. For that I am doing something like:

myLog('['. __FILE__ . ']' . '[' . __CLASS__ . ']' . '[' . __FUNCTION__ . ']' . '[' . __LINE__ . ']');

The problem is everywhere I've to repeat that code in the parameter. and If I want to change the format, I've to change everywhere.

How can I have something like:

myLog(LOG_MSG_FORMAT);

With PHP define it is not possible since it will give my the LINE number of the place where that definition is, not where the definition is getting used.

Any solution to this is welcome. I am not bitchy about having C like functionality of #def.

EDIT: The function does not necessarily be called only in case of errors. It is just that I want to log the the file, line, etc. wherever I am calling that function. So if I just paste a code somewhere "", it should log the line, etc.

For example:

<?php
...
...
<log this location>
...
...
<log this location>
+2  A: 

debug_backtrace()

Col. Shrapnel
+1  A: 

PHP has no preprocessor like C. But you could use your own error handler and use the already mentioned debug_backtrace in it to get the required information.

Gumbo
edited the question.
Sabya
A: 

as others said, you can use debug_backtrace to find out the calling location of your log function. debug_backtrace is quite inconsistent, therefore there is some trickery involved, here's an example:

// helper
function e($a, $k, $d = null) { 
    return isset($a[$k]) ? $a[$k] : $d; 
}

function mylog($msg) {
    $t0 = e(debug_backtrace(), 0);
    $t1 = e(debug_backtrace(), 1);

    $header = sprintf("%s:%s (%s:%s)",
        e($t1, 'class', 'global'),
        e($t1, 'function', 'unknown'),
        e($t0, 'file'),
        e($t0, 'line'));

    $_ = func_get_args();
    $s = $header . ': ' . vsprintf(array_shift($_), $_);

    echo $s, "\n"; // or error_log
}

As a free bonus, my_log also accepts a parameter list in printf style, e.g.

 my_log("send mail to=%s subject=%s time=%d", $to, $subject, time());
stereofrog