Logs.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. /**
  12. * @deprecated 已迁移至Repositorys目录
  13. */
  14. class Logs extends Repository
  15. {
  16. /**
  17. * 合并LogsCron功能 - 读取定时任务日志
  18. */
  19. public function getCronLogs()
  20. {
  21. $path = storage_path('logs/cron.log');
  22. return self::read($path);
  23. }
  24. /**
  25. * 合并Logs2功能 - 读取CLI日志
  26. */
  27. public function getCliLogs()
  28. {
  29. $path = storage_path('logs/cli.log');
  30. return self::read($path);
  31. }
  32. public function get(Grid\Model $model)
  33. {
  34. $list = [];
  35. /**
  36. * @var \Monolog\Logger $loger
  37. */
  38. $loger = Log::getLogger();
  39. /**
  40. * @var \Monolog\Handler\StreamHandler $handler
  41. */
  42. $handler = $loger->getHandlers()[0];
  43. if ($handler instanceof StreamHandler) {
  44. $file = $handler->getUrl();
  45. $list = self::read($file,100);
  46. // dump($list);
  47. }
  48. return $list;
  49. }
  50. static public function read($file, $lineNumber = 30)
  51. {
  52. $f = fopen($file, 'r');
  53. $cursor = -1;
  54. fseek($f, $cursor, SEEK_END);
  55. $char = fgetc($f);
  56. /**
  57. * Trim trailing newline chars of the file
  58. * 修剪文件的尾部换行符
  59. */
  60. while ($char === "\n" || $char === "\r") {
  61. fseek($f, $cursor--, SEEK_END);
  62. $char = fgetc($f);
  63. }
  64. $res = [];
  65. foreach (range(0, $lineNumber) as $a) {
  66. $line = '';
  67. /**
  68. * Read until the start of file or first newline char
  69. * 读取到文件开头或第一个换行符
  70. */
  71. while ($char !== false && $char !== "\n" && $char !== "\r") {
  72. // dump($char,$cursor);
  73. /**
  74. * Prepend the new char
  75. * 前置新的char
  76. */
  77. $line = $char . $line;
  78. fseek($f, $cursor--, SEEK_END);
  79. $char = fgetc($f);
  80. // dump($char);
  81. }
  82. // $cursor--;
  83. fseek($f, $cursor--, SEEK_END);
  84. $char = fgetc($f);
  85. $res[] = [
  86. 'id' => $a,
  87. 'content' => $line
  88. ];
  89. }
  90. return $res;
  91. }
  92. }