tohokuaikiのチラシの裏

技術的ネタとか。

PHPの簡易デバッグ関数

とりあえず。

<?php

function dlog($msg = '', $logfile = null)
{
//    $logfile = dirname(__FILE__).'/debug_log';
    $d = debug_backtrace();
    
    // get called line
    $line = 0;
    $file = '';
    foreach ($d as $_d){
        if ($_d['function'] == __FUNCTION__){
            $line = $_d['line'];
            $file = $_d['file'];
            break;
        }
    }
    
    $e = array_shift($d);
    if (!count($d) == 0){
        $e = array_shift($d);
    }
    
    $s = sprintf("File:%s [Line:%d] %s%s%s", $file, $line,
                isset($e['class']) ? $e['class'] : '<No Class>',
                isset($e['type'])  ? $e['type']  : '',
                $e['function']);
    
    if (strncasecmp($_SERVER['OS'], 'win', 3) === 0){
        if (function_exists('mb_convert_encoding')){
            $s = mb_convert_encoding($s, 'UTF-8', 'SJIS-win');
        }
    }
    
    $s .= ' '. str_replace(array("\n", "\r"), '', $msg);
    $s .= "\n";
    
    if (is_null($logfile)){
        echo $s;
    }
    else {
        if ($fp = fopen($logfile, 'a')){
            fputs($fp, $s);
            fclose($fp);
        }
    }
}