Home  >  Article  >  Backend Development  >  PHP调试函数和日志记录函数分享_PHP

PHP调试函数和日志记录函数分享_PHP

WBOY
WBOYOriginal
2016-05-31 13:17:39840browse

网站程序开发过程经常需要调试,发布阶段也需要记录运行日志,方便发现问题和还原事件。这就要求有调试和日志记录功能。

下面分别写了用于调试的函数和用于记录错误的函数。

使用方法很简单,且自动根据日期生成日志文件:

代码如下:


//调试时,多个参数都可以:
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'); 

Statement:
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