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;
}
}
~~~
結果
