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 $this->stream = fopen($this->url, 'a');
119 $formattedLog = $this->formatLog($level, $message, $context);
120 fwrite($this->stream, $formattedLog);
124 * Formats a log record for the syslog output
126 * @param int $level The loglevel/priority
127 * @param string $message The message
128 * @param array $context The context of this call
130 * @return string the formatted syslog output
132 private function formatLog($level, $message, $context = [])
134 $record = $this->introspection->getRecord();
135 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
138 $logMessage .= DateTimeFormat::localNow() . ' ';
139 $logMessage .= $this->channel . ' ';
140 $logMessage .= '[' . strtoupper($level) . ']: ';
141 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
142 $logMessage .= @json_encode($context) . ' - ';
143 $logMessage .= @json_encode($record);
144 $logMessage .= PHP_EOL;
149 private function checkStream()
151 if (is_resource($this->stream)) {
155 if (empty($this->url)) {
156 throw new \LogicException('Missing stream URL.');
160 set_error_handler([$this, 'customErrorHandler']);
161 $this->stream = fopen($this->url, 'ab');
162 restore_error_handler();
164 if (!is_resource($this->stream)) {
165 $this->stream = null;
167 throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
171 private function createDir()
174 $pos = strpos($this->url, '://');
176 $dirname = dirname($this->url);
179 if (substr($this->url, 0, 7) === 'file://') {
180 $dirname = dirname(substr($this->url, 7));
183 if (isset($dirname) && !is_dir($dirname)) {
184 set_error_handler([$this, 'customErrorHandler']);
185 $status = mkdir($dirname, 0777, true);
186 restore_error_handler();
188 if (!$status && !is_dir($dirname)) {
189 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
194 private function customErrorHandler($code, $msg)
196 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);