YiluPHP
这家伙很懒,什么都没有留下...

经验 一个PHP写日志的函数

浏览数 192478
/*
 * 写日志
 * $level 定义值:DEBUG调试、ERROR错误、VISIT访问、RESPONSE应答、TRACE代码追溯、WARNING警告、NOTICE通知
 * 其它可以自定义,直接传level值过来就行了,输出时日志文件名以$level值结尾
 */
function write_applog($level, $data='')
{
    $level = strtoupper($level);
    if ($level == 'TRACE') {
        $txt = date('Y-m-d H:i:s ').$_SERVER['REQUEST_URI'].' , GET:'.json_encode($_GET).' POST:'.json_encode($_POST).' , RESPONSE: '.$data;
        $code = mb_detect_encoding($txt);
        if ($code!='UTF-8'){
            $txt = iconv($code, 'UTF-8', $txt);
        }
        $a = debug_backtrace();
        array_shift($a);
        foreach ($a as $value) {
            $txt .= "\n\t\t".'file:'.$value['file'].', line:'.$value['line'];
            unset($value['file'], $value['line']);
            $txt .= json_encode($value);
        }
    }
    else if ($level == 'VISIT') {
        $txt = date('Y-m-d H:i:s ').$_SERVER['REQUEST_URI'].' , GET:'.json_encode($_GET).' POST:'.json_encode($_POST);
    }
    else if ($level == 'RESPONSE') {
        $txt = date('Y-m-d H:i:s ').$_SERVER['REQUEST_URI'].' , GET:'.json_encode($_GET).' POST:'.json_encode($_POST).' , RESPONSE: '.$data;
    }
    $path = '../logs/applog/'.date('Ym').'/';
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }
    $code = mb_detect_encoding($txt);
    if ($code!='UTF-8'){
        $txt = iconv($code, 'UTF-8', $txt);
    }
    file_put_contents($path.date('d').'-'.$level.'.log', $txt."\n", FILE_APPEND);
    // $fh = fopen($path.date('d').'-'.$level.'.log', "a");
    // fwrite($fh, $txt."\n");
    // fclose($fh);
}
我来说说