Home >Backend Development >PHP Tutorial >How to write a logging function in php
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 the variable (address) $user_address to the log. We hope This is what is written in the log:
`xx-xx-xx xx:xx $user_address: xxxxx, Yangpu District, Shanghai
Then each log must be line-wrapped, with date and time,
assuming the function name is log ();
We want to call him log('
Then if $user_address is an array and I want to output all of the 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 a string.
The log function can be written like this
<code><span>log</span>(){ <span>$args</span> = func_get_args();<span>//获得传入的所有参数的数组</span><span>$numargs</span> = func_num_args(); <span>//参数的个数</span><span>if</span> (<span>$numargs</span> == <span>0</span>) { <span>$log</span> = <span>""</span>; } elseif (<span>$numargs</span> == <span>1</span>) { <span>$log</span> = <span>$args</span>[<span>0</span>]; } <span>else</span> { <span>$format</span> = array_shift(<span>$args</span>); <span>//分割掉函数第一个元素,并且做返回值返回,'$user_address:%s'</span><span>$log</span> = vsprintf(<span>$format</span>, <span>$args</span>); <span>//把参数代入$format中,</span> } <span>$log</span> = <span>date</span>(<span>"[Y/m/d H:i:s] "</span>) . <span>$log</span> . PHP_EOL;<span>//加上时间</span><span>$file</span> = <span>'/usr/share/nginx/html/log.log'</span>; <span>$fp</span> = <span>fopen</span>(<span>$file</span>, <span>'a'</span>); <span>fwrite</span>(<span>$fp</span>, <span>$log</span>); <span>fclose</span>(<span>$fp</span>); <span>return</span> true; } </code>
Usage:
1. Print the general variable $a, log('got the value of $a: %s',$a );
2 . Print an array $arr
log('%s',print_r( $arr,true));
The above introduces how to use PHP to write a log function, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.