TP5.1日志处理

thinkphp\library\think\db\Connection.php

line: 682

public function query($sql, $bind = [], $master = false, $pdo = false)
{

    try {
    ...
    }catch (\PDOException $e) {
        if ($this->isBreak($e)) {
            return $this->close()->query($sql, $bind, $master, $pdo);
        }
        var_dump( $e->getMessage() .' [SQL语句]'.$sql );
        \Xlog\XLogKit::logger("_sql")->error($e->getMessage() .' [SQL语句]'.$sql);
        throw new PDOException($e, $this->config, $this->getLastsql());
    }
}

debug日志

protected function debug($start, $sql = '', $master = false){
  
    if (!empty($this->config['debug'])) {
               // SQL性能分析
               if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
                   $result = $this->getExplain($sql);
               }
                // SQL监听
                $this->triggerSql($sql, $runtime, $result, $master);

                //SQL记录
                if (isset($_SERVER["LOG_SQL"]) && $_SERVER["LOG_SQL"] == 1) {
                    \Xlog\XLogKit::logger("_sql")->info( $sql.' [ RunTime:'.$runtime.'s ]');
                }
    }
}

 

错误日志

thinkphp\library\think\exception\Handle.php

line:84

public function render(Exception $e)
{
	if ($this->render && $this->render instanceof \Closure) {
		$result = call_user_func_array($this->render, [$e]);

		if ($result) {
			return $result;
		}
	}

	if ($e instanceof HttpException) {
		//写log
		\Xlog\XLogKit::logger("_sys")->error('[errmsg]'.$e->getMessage() .', [line]' . $e->getLine() .',[file]' . $e->getFile());
		return $this->renderHttpException($e);
	} else {
		//写log
		\Xlog\XLogKit::logger("_sys")->error('[errmsg]'.$e->getMessage() .', [line]' . $e->getLine() .',[file]' . $e->getFile());
		return $this->convertExceptionToResponse($e);
	}
}

 

接管日志debug  ( 开启数据库的调试模式 )

public function sqlListen(){
	Db::listen(function ($sql, $time, $explain, $master) {
		// 记录SQL
		echo $sql . ' [' . $time . 's] ' . ($master ? 'master' : 'slave') .'<br/>';
		// 查看性能分析结果
		//dump($explain);
	});
}

 

异常

// 自定义异常页面的模板文件
 'exception_tmpl' => Env::get('app_path') . 'template/exception.tpl',

接管异常

    // 异常处理handle类 留空使用 \think\exception\Handle
    'exception_handle'       => '\\app\\common\\exception\\Http',

需要继承 think\exception\Handle 且实现 render 方法

<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;

class Http extends Handle
{
    public function render(Exception $e)
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }

        // 请求异常
        if ($e instanceof HttpException && request()->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 其他错误交给系统处理
        return parent::render($e);
    }

}