Logs.php 2.4 KB

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