|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Wcms; |
| 4 | + |
| 5 | +use DateTime; |
| 6 | +use DateTimeInterface; |
| 7 | +use RuntimeException; |
| 8 | + |
| 9 | +class Logline |
| 10 | +{ |
| 11 | + public DateTime $date; |
| 12 | + public string $level; |
| 13 | + public string $ref; |
| 14 | + public string $message; |
| 15 | + public string $in = ''; |
| 16 | + |
| 17 | + public const LEVELS = ['ERROR', 'WARN', 'INFO', 'DEBUG']; |
| 18 | + |
| 19 | + /** |
| 20 | + * @throws RuntimeException if parsing failed |
| 21 | + */ |
| 22 | + public function __construct(string $line) |
| 23 | + { |
| 24 | + $length = strlen($line); |
| 25 | + $date = substr($line, 0, 25); |
| 26 | + $datetime = DateTime::createFromFormat(DateTimeInterface::ATOM, $date); |
| 27 | + |
| 28 | + if ($datetime === false) { |
| 29 | + throw new RuntimeException("Date $date is not parsable from '$line'"); |
| 30 | + } |
| 31 | + $this->date = $datetime; |
| 32 | + |
| 33 | + $level = substr($line, 28, 5); |
| 34 | + $level = trim($level); |
| 35 | + if (in_array($level, self::LEVELS)) { |
| 36 | + $this->level = strtolower($level); |
| 37 | + } |
| 38 | + |
| 39 | + $rest = substr($line, 36); |
| 40 | + |
| 41 | + $refpos = strpos($rest, ' '); |
| 42 | + |
| 43 | + if ($refpos === false) { |
| 44 | + throw new RuntimeException(); |
| 45 | + } |
| 46 | + $this->ref = substr($rest, 0, $refpos); |
| 47 | + |
| 48 | + $rest = substr($rest, $refpos + 1); |
| 49 | + |
| 50 | + $inpos = strrpos($rest, ' in /'); |
| 51 | + |
| 52 | + if ($inpos === false) { |
| 53 | + $this->message = $rest; |
| 54 | + } else { |
| 55 | + $this->message = substr($rest, 0, $inpos); |
| 56 | + $this->in = substr($rest, $inpos + 4); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments