企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
1.更改tp5日志存放的目录 ``` 在index.php中重新定义常量LOG_PATH ``` ~~~ <?php // [ 应用入口文件 ] // 定义应用目录 define('APP_PATH', __DIR__ . '/application/'); define('LOG_PATH', __DIR__. '/log/'); // 加载框架引导文件 require __DIR__ . '/thinkphp/start.php'; ~~~ 2.关闭tp5自带日志记录 ``` 在配置文件中更改log下的type为test ``` ~~~ 'log' => [ // 日志记录方式,内置 file socket 支持扩展 //'type' => 'File', 'type' => 'test', // 日志保存目录 'path' => LOG_PATH, // 日志记录级别 'level' => [], ], ~~~ 3.更改`app\lib\exception`下新建ExceptionHandler.php文件 ~~~ <?php namespace app\lib\exception; use Exception; use think\exception\Handle; use think\Request; use think\Log; class ExceptionHandler extends Handle { private $code; private $msg; private $errorCode; public function render(Exception $e) { if ($e instanceof BaseException) { //如果是自定义异常,则控制http状态码,不需要记录日志 //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常 //不应当记录日志 $this->code = $e->code; $this->msg = $e->msg; $this->errorCode = $e->errorCode; } else{ // 如果是服务器未处理的异常,将http状态码设置为500,并记录日志 $this->code = 500; //$this->msg = 'sorry,we make a mistake. (^o^)Y'; $this->msg = 'sorry,服务器内部错误, (^o^)Y'; $this->errorCode = 999; $this->recordErrorLog($e); } $request = Request::instance(); $result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => $request = $request->url() ]; return json($result, $this->code); } /* * 将异常写入日志 */ private function recordErrorLog(Exception $e) { Log::init([ 'type' => 'File', 'path' => LOG_PATH, 'level' => ['error'] ]); // Log::record($e->getTraceAsString()); Log::record($e->getMessage(),'error'); } } ~~~ 4.更改控制器下的Banner.php文件 ~~~ <?php namespace app\api\controller\v1; use app\api\validate\IDMustBePostiveInt; use app\api\model\Banner as BannerModel; use app\lib\exception\BannerMissException; use think\Exception; class Banner{ //获取指定id的banner信息 public function getBanner($id) { (new IDMustBePostiveInt())->goCheck(); $banner=BannerModel::getBannerByID($id); if(!$banner){ //throw new BannerMissException(); throw new Exception('内部错误'); } return $banner; } } ~~~ 结果 ![](https://box.kancloud.cn/d509adad24785dc49f95b9a607eef542_1311x514.png)