| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
- declare (strict_types = 1);
- namespace app\middleware;
- use Closure;
- use think\Request;
- use think\Response;
- use think\facade\Event;
- use think\response\Json;
- use app\utils\StringsUtil;
- use think\facade\Log as FacadeLog;
- class Log
- {
- /**
- * @var string
- */
- public static $logID = '';
- /**
- * 处理请求
- *
- * @param Request $request
- * @param Closure $next
- * @return Response
- */
- public function handle(Request $request, Closure $next)
- {
- $logId = $request->header('x-request-id');
- if (empty($logId)) {
- $logId = StringsUtil::uuid();
- }
- self::$logID = $logId;
- Event::listen(
- 'think\event\LogWrite',
- function ($event) use ($logId) {
- foreach ($event->log as $logLevel => &$logs) {
- foreach ($logs as &$log) {
- if (is_string($log)) {
- $log = 'trackID:' . $logId . '|' . $log;
- } elseif (is_array($log)) {
- $log['trackID'] = $logId;
- }
- }
- }
- }
- );
- if (strpos(\think\facade\Request::url(), '/monitor') !== false) {
- return \response("");
- }
- $startTime = microtime(true);
- FacadeLog::info(
- 'request_begin|IP:' . get_client_ip(0) . '|UA:' . $_SERVER["HTTP_USER_AGENT"] . '|get:' . json_encode(
- $request->get(),
- JSON_UNESCAPED_UNICODE
- ) . '|post:' . json_encode(
- $request->post(),
- JSON_UNESCAPED_UNICODE
- ) . '|URI:' . $request->url()
- );
- /**
- * @var Response $response
- */
- $response = $next($request);
- $endTime = microtime(true);
- $spendTime = round($endTime - $startTime, 4);
- $data = '';
- if ($response instanceof Json) {
- $data = $response->getData();
- if (!is_string($data)) {
- $data = json_encode($data, JSON_UNESCAPED_UNICODE);
- }
- }
- FacadeLog::info('request_end|spendTime:' . $spendTime . '|response:' . $data);
- return $response;
- }
- }
|