Log.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\middleware;
  4. use app\utils\StringsUtil;
  5. use Closure;
  6. use think\facade\Event;
  7. use think\facade\Log as FacadeLog;
  8. use think\Request;
  9. use think\Response;
  10. use think\response\Json;
  11. class Log
  12. {
  13. /**
  14. * @var string
  15. */
  16. public static $logID = '';
  17. /**
  18. * 处理请求
  19. *
  20. * @param Request $request
  21. * @param Closure $next
  22. * @return Response
  23. */
  24. public function handle(Request $request, Closure $next)
  25. {
  26. $logId = $request->header('x-request-id');
  27. if (empty($logId)) {
  28. $logId = StringsUtil::uuid();
  29. }
  30. self::$logID = $logId;
  31. Event::listen(
  32. 'think\event\LogWrite',
  33. function ($event) use ($logId) {
  34. foreach ($event->log as $logLevel => &$logs) {
  35. foreach ($logs as &$log) {
  36. if (is_string($log)) {
  37. $log = 'trackID:' . $logId . '|' . $log;
  38. } elseif (is_array($log)) {
  39. $log['trackID'] = $logId;
  40. }
  41. }
  42. }
  43. }
  44. );
  45. if (strpos(\think\facade\Request::url(), '/monitor') !== false) {
  46. return \response("");
  47. }
  48. $startTime = microtime(true);
  49. FacadeLog::info(
  50. 'request_begin|IP:' . get_client_ip(0) . '|UA:' . $_SERVER["HTTP_USER_AGENT"] . '|get:' . json_encode(
  51. $request->get(),
  52. JSON_UNESCAPED_UNICODE
  53. ) . '|post:' . json_encode(
  54. $request->post(),
  55. JSON_UNESCAPED_UNICODE
  56. ) . '|URI:' . $request->url()
  57. );
  58. /**
  59. * @var Response $response
  60. */
  61. $response = $next($request);
  62. $endTime = microtime(true);
  63. $spendTime = bcsub(strval($endTime), strval($startTime), 4);
  64. $data = '';
  65. if ($response instanceof Json) {
  66. $data = $response->getData();
  67. if (!is_string($data)) {
  68. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  69. }
  70. }
  71. FacadeLog::info('request_end|spendTime:' . $spendTime . '|response:' . $data);
  72. return $response;
  73. }
  74. }