Home >Backend Development >PHP Tutorial >Use debug_backtrace to customize a basic log printing function (PHP code example)

Use debug_backtrace to customize a basic log printing function (PHP code example)

藏色散人
藏色散人forward
2021-05-31 09:39:392676browse

This article will introduce the common code example of the PHP basic code to you. Use Debug_backtrace to customize a basic log print function. It has a certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Use debug_backtrace to customize a basic log printing function (PHP code example)

Recently I was modifying an ancient ancestral code, but unfortunately it didn’t even have a log printing function, and there was no framework support, so I realized how weak I was.

Recommendation: "PHP Video Tutorial"

When I was looking at other people's code, I discovered that PHP's function debug_backtrace() really solved the pain point of my problem. You can define a function to record the file name and line number when calling the function, so as to know the corresponding printing position.

/**
 * 自定义日志打印,将日志信息写入指定文件,并记录当前调用的文件名与行数
 * @param $data mixed 写入文件的数据
 * @param $file string 文件路径
 */
function put_log($data,$file){

    // 递归创建文件夹
    function created_dir( $dir ){
        return  is_dir ( $dir ) or created_dir(dirname( $dir )) and  mkdir ( $dir , 0777);
    }

    $traces = debug_backtrace();

    if(dirname($file)!='.'){
        created_dir( dirname($file) );
    }

    $str = date('Y-m-d H:i:s')."\n";
    foreach ($traces as $trace){
        $str .= $trace["file"]." 文件第【".$trace["line"]."】行 data:\n";
    }
    $str .= json_encode($data)."\n\n";

    file_put_contents($file,$str,FILE_APPEND);
}

put_log('sss','ss/s/a.txt');

The above is the detailed content of Use debug_backtrace to customize a basic log printing function (PHP code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete