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

藏色散人
Release: 2023-04-10 06:58:01
forward
2550 people have browsed it

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');
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!