3 * @copyright Copyright (C) 2021, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 namespace Friendica\Object\Log;
24 * Parse a log line and offer some utility methods
28 const REGEXP = '/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[^ ]*) (\w+) \[(\w*)\]: (.*)/';
37 public $context = null;
43 public $message = null;
49 public $source = null;
56 * @param string $logline Source log line to parse
58 public function __construct(int $id, string $logline)
61 $this->parse($logline);
64 private function parse($logline)
66 list($logline, $jsonsource) = explode(' - ', $logline);
68 if (strpos($logline, '{"') > 0) {
69 list($logline, $jsondata) = explode('{"', $logline, 2);
70 $jsondata = '{"' . $jsondata;
72 preg_match(self::REGEXP, $logline, $matches);
73 $this->date = $matches[1];
74 $this->context = $matches[2];
75 $this->level = $matches[3];
76 $this->message = $matches[4];
77 $this->data = $jsondata;
78 $this->source = $jsonsource;
79 $this->try_fix_json();
81 $this->logline = $logline;
85 * Fix message / data split
87 * In log boundary between message and json data is not specified.
88 * If message contains '{' the parser thinks there starts the json data.
89 * This method try to parse the found json and if it fails, search for next '{'
90 * in json data and retry
92 private function try_fix_json()
94 if (is_null($this->data) || $this->data == "") {
98 $d = json_decode($this->data, true, 512, JSON_THROW_ON_ERROR);
99 } catch (\JsonException $e) {
100 // try to find next { in $str and move string before to 'message'
102 $pos = strpos($this->data, '{', 1);
104 $this->message .= substr($this->data, 0, $pos);
105 $this->data = substr($this->data, $pos);
106 $this->try_fix_json();
111 * Return decoded `data` as array suitable for template
115 public function get_data() {
116 $data = json_decode($this->data, true);
118 foreach($data as $k => $v) {
119 $v = print_r($v, true);
127 * Return decoded `source` as array suitable for template
131 public function get_source() {
132 return json_decode($this->source, true);