Logs.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace App\Module\System\Repositories;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Repositories\Repository;
  5. use Illuminate\Support\Facades\Log;
  6. use Monolog\Handler\StreamHandler;
  7. /**
  8. * 日志读取
  9. *
  10. */
  11. class Logs extends Repository
  12. {
  13. public function get(Grid\Model $model)
  14. {
  15. $list = [];
  16. /**
  17. * @var \Monolog\Logger $loger
  18. */
  19. $loger = Log::getLogger();
  20. /**
  21. * @var \Monolog\Handler\StreamHandler $handler
  22. */
  23. $handler = $loger->getHandlers()[0];
  24. if ($handler instanceof StreamHandler) {
  25. $file = $handler->getUrl();
  26. $list = self::read($file,100);
  27. // dump($list);
  28. }
  29. return $list;
  30. }
  31. static public function read($file, $lineNumber = 30)
  32. {
  33. $f = fopen($file, 'r');
  34. $cursor = -1;
  35. fseek($f, $cursor, SEEK_END);
  36. $char = fgetc($f);
  37. /**
  38. * Trim trailing newline chars of the file
  39. * 修剪文件的尾部换行符
  40. */
  41. while ($char === "\n" || $char === "\r") {
  42. fseek($f, $cursor--, SEEK_END);
  43. $char = fgetc($f);
  44. }
  45. $res = [];
  46. foreach (range(0, $lineNumber) as $a) {
  47. $line = '';
  48. /**
  49. * Read until the start of file or first newline char
  50. * 读取到文件开头或第一个换行符
  51. */
  52. while ($char !== false && $char !== "\n" && $char !== "\r") {
  53. // dump($char,$cursor);
  54. /**
  55. * Prepend the new char
  56. * 前置新的char
  57. */
  58. $line = $char . $line;
  59. fseek($f, $cursor--, SEEK_END);
  60. $char = fgetc($f);
  61. // dump($char);
  62. }
  63. // $cursor--;
  64. fseek($f, $cursor--, SEEK_END);
  65. $char = fgetc($f);
  66. $res[] = [
  67. 'id' => $a,
  68. 'content' => $line
  69. ];
  70. }
  71. return $res;
  72. }
  73. }