网站程序开发过程经常需要调试,发布阶段也需要记录运行日志,方便发现问题和还原事件。这就要求有调试和日志记录功能。
下面分别写了用于调试的函数和用于记录错误的函数。
使用方法很简单,且自动根据日期生成日志文件:
代码如下:
//调试时,多个参数都可以:
sysdebug(hello);
sysdebug(hello, tiger is coming now);
//错误记录也一样:
syserror(error);
syserror(error, unfortunately tiger is dead , we are sad);
php调试和日志记录函数,如下:
代码如下:
/**
* 记录调试信息
*/
function sysdebug($msg) {
if (defined(debug_mode)) {
//todo 检测调试开关,发布时不打印
$params = func_get_args();
$traces = debug_backtrace();
$trace = array_pop($traces);
sysrecord($params, $trace, 'debug');
}
}
/**
* 记录错误信息
*/
function syserror($msg) {
$params = func_get_args();
$traces = debug_backtrace();
$trace = array_pop($traces);
sysrecord($params, $trace, 'error');
}
/**
* 写文件
* @ignore
*/
function sysfile($filename, $msg, $mode = null) {
$path = dirname($filename);
if (!file_exists($path)) {
mkdir($path, 0666, true);
}
$flag = lock_ex;
if ($mode) {
switch ($mode) {
case add:
$flag = file_append | lock_ex;
break;
case a:
$flag = file_append | lock_ex;
break;
default:
break;
}
}
file_put_contents($filename, $msg, $flag);
}
/**
* 记录信息
* @ignore
*/
function sysrecord($params, $trace, $level) {
$path = dirname(__file__) . /logs/;
//todo 日志保存目录最好修改一下
$file = $trace['file'];
$func = $trace['function'];
if ($func == sys$level) {
$func = '';
}
$filename = $path . $level/ . date(y-m-d) . '.log';
$msg = [ . date(m-d h:i:s) . ] file:\ . basename($file) . \ func:\ . $func . \ msg: . json_encode($params) . \r\n;
sysfile($filename, $msg, 'add');
}