thinkphp5异常处理,输出日志

Model

Controller

goCheck();
        $banner = BannerModel::getBannerByID($id);
        if(!$banner){
            throw new Exception('内部错误');
        }
        return $banner;
    }
}

Exception

code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            $this->code=500;
            $this->msg = "服务器内部错误,不能告诉你";
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }
        $request = Request::instance();
        $result = [
            'msg'=>$this->msg,
            'errorCode'=>$this->errorCode,
            'request_url'=> $request->url(),

        ];
        return json($result,$this->code);
    }
    public function recordErrorLog(Exception $e){
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error'],

        ]);
        Log::record($e->getMessage(),'error');
    }
}

注:1.修改了LOG_PATH位置:define('LOG_PATH',__DIR__ . '/../log/');

       2.修改了config.php:  

'log'                    => [
        // 日志记录方式,内置 file socket 支持扩展
        'type'  => 'test',
        // 日志保存目录
        'path'  => LOG_PATH,
        // 日志记录级别
        'level' => [],
    ],

把File改为test

    3.抛出异常,处理异常的同时输出Log日志信息

为Log输出代码
$this->recordErrorLog($e);

 public function recordErrorLog(Exception $e){
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error'],

        ]);
        Log::record($e->getMessage(),'error');
    }

    4.抛出异常过程辅助理解

 

结果:

[ 2019-07-12T17:51:52+08:00 ] ::1 ::1 GET /zerg/public/index.php/api/v1.Banner/getBanner?id=3
[ log ] localhost/zerg/public/index.php/api/v1.Banner/getBanner?id=3 [运行时间:0.062730s][吞吐率:15.94req/s] [内存消耗:1,144.04kb] [文件加载:33]
[ error ] [0]内部错误[E:\phpStudy\PHPTutorial\WWW\zerg\application\api\controller\v1\Banner.php:29]
[ error ] 内部错误

你可能感兴趣的:(异常,tp5)