3 namespace Friendica\Util\Logger;
5 use Friendica\Util\DateTimeFormat;
6 use Friendica\Util\Introspection;
10 * A Logger instance for logging into a stream (file, stdout, stderr)
12 class StreamLogger extends AbstractLogger
15 * The minimum loglevel at which this logger will be triggered
21 * The file URL of the stream (if needed)
27 * The stream, where the current logger is writing into
33 * The current process ID
42 private $errorMessage;
45 * Translates LogLevel log levels to integer values
48 private $levelToInt = [
49 LogLevel::EMERGENCY => 0,
51 LogLevel::CRITICAL => 2,
53 LogLevel::WARNING => 4,
54 LogLevel::NOTICE => 5,
61 * @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
62 * @param string $level The minimum loglevel at which this logger will be triggered
66 public function __construct($channel, $stream, Introspection $introspection, $level = LogLevel::DEBUG)
68 parent::__construct($channel, $introspection);
70 if (is_resource($stream)) {
71 $this->stream = $stream;
72 } elseif (is_string($stream)) {
75 throw new \InvalidArgumentException('A stream must either be a resource or a string.');
78 $this->pid = getmypid();
79 if (array_key_exists($level, $this->levelToInt)) {
80 $this->logLevel = $this->levelToInt[$level];
82 throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
86 public function close()
88 if ($this->url && is_resource($this->stream)) {
89 fclose($this->stream);
96 * Adds a new entry to the log
99 * @param string $message
100 * @param array $context
104 protected function addEntry($level, $message, $context = [])
106 if (!array_key_exists($level, $this->levelToInt)) {
107 throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
110 $logLevel = $this->levelToInt[$level];
112 if ($logLevel > $this->logLevel) {
116 $this->checkStream();
118 $formattedLog = $this->formatLog($level, $message, $context);
119 fwrite($this->stream, $formattedLog);
123 * Formats a log record for the syslog output
125 * @param int $level The loglevel/priority
126 * @param string $message The message
127 * @param array $context The context of this call
129 * @return string the formatted syslog output
131 private function formatLog($level, $message, $context = [])
133 $record = $this->introspection->getRecord();
134 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
137 $logMessage .= DateTimeFormat::utcNow() . ' ';
138 $logMessage .= $this->channel . ' ';
139 $logMessage .= '[' . strtoupper($level) . ']: ';
140 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
141 $logMessage .= @json_encode($context) . ' - ';
142 $logMessage .= @json_encode($record);
143 $logMessage .= PHP_EOL;
148 private function checkStream()
150 if (is_resource($this->stream)) {
154 if (empty($this->url)) {
155 throw new \LogicException('Missing stream URL.');
159 set_error_handler([$this, 'customErrorHandler']);
160 $this->stream = fopen($this->url, 'ab');
161 restore_error_handler();
163 if (!is_resource($this->stream)) {
164 $this->stream = null;
166 throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
170 private function createDir()
173 $pos = strpos($this->url, '://');
175 $dirname = dirname($this->url);
178 if (substr($this->url, 0, 7) === 'file://') {
179 $dirname = dirname(substr($this->url, 7));
182 if (isset($dirname) && !is_dir($dirname)) {
183 set_error_handler([$this, 'customErrorHandler']);
184 $status = mkdir($dirname, 0777, true);
185 restore_error_handler();
187 if (!$status && !is_dir($dirname)) {
188 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
193 private function customErrorHandler($code, $msg)
195 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);