Browse Source

chore: 日志记录

master
liyang 1 month ago
parent
commit
fc9879b847
  1. 14
      app/ExceptionHandle.php
  2. 10
      app/home/middleware/ApiLogMiddleware.php

14
app/ExceptionHandle.php

@ -1,4 +1,5 @@
<?php
namespace app;
use think\db\exception\DataNotFoundException;
@ -7,6 +8,7 @@ use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Log;
use think\Response;
use Throwable;
@ -50,8 +52,18 @@ class ExceptionHandle extends Handle
*/
public function render($request, Throwable $e): Response
{
// 统一写日志
Log::error('System Exception' . json_encode([
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]));
// return json([
// 'code' => 100500,
// 'message' => 'System error',
// ]);
// 添加自定义异常处理机制
// 其他错误交给系统处理
return parent::render($request, $e);
}

10
app/home/middleware/ApiLogMiddleware.php

@ -40,8 +40,14 @@ class ApiLogMiddleware
if ($request->method(true) === 'OPTIONS') {
return response()->send();
}
$response = $next($request);
$path = $request->pathinfo();
$shouldLog = in_array($path, $this->logRoutes);
$responseData = $response instanceof Response ? $response->getData() : null;
// 如果接口返回错误码,也记录日志
if ($responseData && isset($responseData['code']) && $responseData['code'] != 0) {
$shouldLog = true;
}
$logData = [];
if ($shouldLog) {
$ip = (new BaseHomeService())->getClientRealIp();
@ -58,11 +64,9 @@ class ApiLogMiddleware
}
}
$response = $next($request);
if ($shouldLog && $response instanceof Response) {
$logData['response'] = $response->getData();
$logData['response'] = $responseData;
}
//写入redis
if (!empty($logData)) {

Loading…
Cancel
Save