3 * @copyright Copyright (C) 2010-2023, the Friendica project
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/>.
22 namespace Friendica\Core\Logger\Type;
24 use Friendica\Core\Config\Capability\IManageConfigValues;
25 use Friendica\Core\Hooks\Capabilities\IAmAStrategy;
26 use Friendica\Core\Logger\Capabilities\IHaveCallIntrospections;
27 use Friendica\Core\Logger\Exception\LoggerArgumentException;
28 use Friendica\Core\Logger\Exception\LoggerException;
29 use Friendica\Core\Logger\Exception\LogLevelException;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\FileSystem;
35 * A Logger instance for logging into a stream (file, stdout, stderr)
37 class StreamLogger extends AbstractLogger implements IAmAStrategy
40 * The minimum loglevel at which this logger will be triggered
46 * The file URL of the stream (if needed)
52 * The stream, where the current logger is writing into
58 * The current process ID
69 * Translates LogLevel log levels to integer values
72 private $levelToInt = [
73 LogLevel::EMERGENCY => 0,
75 LogLevel::CRITICAL => 2,
77 LogLevel::WARNING => 4,
78 LogLevel::NOTICE => 5,
85 * @param string $level The minimum loglevel at which this logger will be triggered
87 * @throws LoggerArgumentException
88 * @throws LogLevelException
90 public function __construct(string $channel, IManageConfigValues $config, IHaveCallIntrospections $introspection, FileSystem $fileSystem, string $level = LogLevel::DEBUG)
92 $this->fileSystem = $fileSystem;
94 $stream = $this->logfile ?? $config->get('system', 'logfile');
95 if ((@file_exists($stream) && !@is_writable($stream)) || @is_writable(basename($stream))) {
96 throw new LoggerArgumentException(sprintf('%s is not a valid logfile', $stream));
99 parent::__construct($channel, $introspection);
101 if (is_resource($stream)) {
102 $this->stream = $stream;
103 } elseif (is_string($stream)) {
104 $this->url = $stream;
106 throw new LoggerArgumentException('A stream must either be a resource or a string.');
109 $this->pid = getmypid();
110 if (array_key_exists($level, $this->levelToInt)) {
111 $this->logLevel = $this->levelToInt[$level];
113 throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
116 $this->checkStream();
119 public function close()
121 if ($this->url && is_resource($this->stream)) {
122 fclose($this->stream);
125 $this->stream = null;
129 * Adds a new entry to the log
131 * @param mixed $level
132 * @param string $message
133 * @param array $context
137 * @throws LoggerException
138 * @throws LogLevelException
140 protected function addEntry($level, string $message, array $context = [])
142 if (!array_key_exists($level, $this->levelToInt)) {
143 throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
146 $logLevel = $this->levelToInt[$level];
148 if ($logLevel > $this->logLevel) {
152 $this->checkStream();
154 $formattedLog = $this->formatLog($level, $message, $context);
155 fwrite($this->stream, $formattedLog);
159 * Formats a log record for the syslog output
161 * @param mixed $level The loglevel/priority
162 * @param string $message The message
163 * @param array $context The context of this call
165 * @return string the formatted syslog output
167 * @throws LoggerException
169 private function formatLog($level, string $message, array $context = []): string
171 $record = $this->introspection->getRecord();
172 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
175 $logMessage = DateTimeFormat::utcNow(DateTimeFormat::ATOM) . ' ';
176 } catch (\Exception $exception) {
177 throw new LoggerException('Cannot get current datetime.', $exception);
179 $logMessage .= $this->channel . ' ';
180 $logMessage .= '[' . strtoupper($level) . ']: ';
181 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
182 $logMessage .= $this->jsonEncodeArray($context) . ' - ';
183 $logMessage .= $this->jsonEncodeArray($record);
184 $logMessage .= PHP_EOL;
190 * Checks the current stream
192 * @throws LoggerException
193 * @throws LoggerArgumentException
195 private function checkStream()
197 if (is_resource($this->stream)) {
201 if (empty($this->url)) {
202 throw new LoggerArgumentException('Missing stream URL.');
206 $this->stream = $this->fileSystem->createStream($this->url);
207 } catch (\UnexpectedValueException $exception) {
208 throw new LoggerException('Cannot create stream.', $exception);