LogViewer.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. <?php
  2. /**
  3. * @package Grav\Common\Helpers
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Helpers;
  9. class LogViewer
  10. {
  11. protected $pattern = '/\[(?P<date>.*)\] (?P<logger>\w+).(?P<level>\w+): (?P<message>.*[^ ]+) (?P<context>[^ ]+) (?P<extra>[^ ]+)/';
  12. /**
  13. * Get the objects of a tailed file
  14. *
  15. * @param string $filepath
  16. * @param int $lines
  17. * @param bool $desc
  18. * @return array
  19. */
  20. public function objectTail($filepath, $lines = 1, $desc = true)
  21. {
  22. $data = $this->tail($filepath, $lines);
  23. $tailed_log = explode(PHP_EOL, $data);
  24. $line_objects = [];
  25. foreach ($tailed_log as $line) {
  26. $line_objects[] = $this->parse($line);
  27. }
  28. return $desc ? $line_objects : array_reverse($line_objects);
  29. }
  30. /**
  31. * Optimized way to get just the last few entries of a log file
  32. *
  33. * @param string $filepath
  34. * @param int $lines
  35. * @return bool|string
  36. */
  37. public function tail($filepath, $lines = 1) {
  38. $f = @fopen($filepath, "rb");
  39. if ($f === false) return false;
  40. else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
  41. fseek($f, -1, SEEK_END);
  42. if (fread($f, 1) != "\n") $lines -= 1;
  43. // Start reading
  44. $output = '';
  45. $chunk = '';
  46. // While we would like more
  47. while (ftell($f) > 0 && $lines >= 0) {
  48. // Figure out how far back we should jump
  49. $seek = min(ftell($f), $buffer);
  50. // Do the jump (backwards, relative to where we are)
  51. fseek($f, -$seek, SEEK_CUR);
  52. // Read a chunk and prepend it to our output
  53. $output = ($chunk = fread($f, $seek)) . $output;
  54. // Jump back to where we started reading
  55. fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
  56. // Decrease our line counter
  57. $lines -= substr_count($chunk, "\n");
  58. }
  59. // While we have too many lines
  60. // (Because of buffer size we might have read too many)
  61. while ($lines++ < 0) {
  62. // Find first newline and remove all text before that
  63. $output = substr($output, strpos($output, "\n") + 1);
  64. }
  65. // Close file and return
  66. fclose($f);
  67. return trim($output);
  68. }
  69. /**
  70. * Helper class to get level color
  71. *
  72. * @param string $level
  73. * @return mixed|string
  74. */
  75. public static function levelColor($level)
  76. {
  77. $colors = [
  78. 'DEBUG' => 'green',
  79. 'INFO' => 'cyan',
  80. 'NOTICE' => 'yellow',
  81. 'WARNING' => 'yellow',
  82. 'ERROR' => 'red',
  83. 'CRITICAL' => 'red',
  84. 'ALERT' => 'red',
  85. 'EMERGENCY' => 'magenta'
  86. ];
  87. return $colors[$level] ?? 'white';
  88. }
  89. /**
  90. * Parse a monolog row into array bits
  91. *
  92. * @param string $line
  93. * @return array
  94. */
  95. public function parse($line)
  96. {
  97. if( !is_string($line) || strlen($line) === 0) {
  98. return array();
  99. }
  100. preg_match($this->pattern, $line, $data);
  101. if (!isset($data['date'])) {
  102. return array();
  103. }
  104. preg_match('/(.*)- Trace:(.*)/', $data['message'], $matches);
  105. if (is_array($matches) && isset($matches[1])) {
  106. $data['message'] = trim($matches[1]);
  107. $data['trace'] = trim($matches[2]);
  108. }
  109. return array(
  110. 'date' => \DateTime::createFromFormat('Y-m-d H:i:s', $data['date']),
  111. 'logger' => $data['logger'],
  112. 'level' => $data['level'],
  113. 'message' => $data['message'],
  114. 'trace' => isset($data['trace']) ? $this->parseTrace($data['trace']) : null,
  115. 'context' => json_decode($data['context'], true),
  116. 'extra' => json_decode($data['extra'], true)
  117. );
  118. }
  119. /**
  120. * Parse text of trace into an array of lines
  121. *
  122. * @param string $trace
  123. * @param int $rows
  124. * @return array
  125. */
  126. public static function parseTrace($trace, $rows = 10)
  127. {
  128. $lines = array_filter(preg_split('/#\d*/m', $trace));
  129. return array_slice($lines, 0, $rows);
  130. }
  131. }