Home>Article>Backend Development> PHP implements a log function
This time I will bring you PHP to implement a log function. What are theprecautions for PHP to implement the log function? The following is a practical case, let's take a look.
This time I will bring you PHP to implement a log function. What are the precautions for PHP to implement the log function? The following is a practical case, let's take a look. We want to write a log function. First we need to understand the requirements. How do we generally use the log function? For example, when the program reaches a certain step, I hope to print the value of this variable (address) $user_address to Log,We hope the log reads like this:
`xx-xx-xx xx:xx $user_address: xxxxx, Yangpu District, Shanghai Then each log Both have line breaks and date and time. Assume the function name is log(); We hope to call it like this log('useraddress:user_address); What if $user_address is an array. I want to output all the contents of an array to the log. What should I do? There is a function called print_r($arg,true). The second parameter means not to output directly. , but the output result is used as the return value. We know that its output result is astring.
log function can be written like this
log(){$args= func_get_args();//获得传入的所有参数的数组$numargs= func_num_args();//参数的个数if($numargs==0) {$log=""; } elseif ($numargs==1) {$log=$args[0]; }else{$format= array_shift ($args);//分割掉函数第一个元素,并且做返回值返回,'$user_address:%s'$log= vsprintf ($format,$args);//把参数代入$format中,}$log=date("[Y/m/d H:i:s] ") .$log. PHP_EOL;//加上时间$file='/usr/share/nginx/html/log.log'$fp=fopen($file,'a');fwrite($fp,$log);fclose($fp);returntrue; }
Usage:1. Print general variable $a,
log('得到了$a的值:%s',$a );2. Print an array $arr
log('%s',print_r($arr,true));
can be used for the above Improve the function
functionlog2($arg){$log= vsprintf('%s', print_r($arg,true));$log= date('[Y/m/d H:i:s]') .'---'.$log. PHP_EOL;$path= dirname(FILE) .'/log.log'$fp= file_put_contents ($path,$log, FILE_APPEND);returntrue; }$a=[1,23,45,45]; log2($a);I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
How to prevent XSS cross-site attacks in Laravel 5
Detailed explanation of the use of PHP array access interface ArrayAccess
The above is the detailed content of PHP implements a log function. For more information, please follow other related articles on the PHP Chinese website!