]> git.mxchange.org Git - friendica.git/blob - src/Util/Logger/StreamLogger.php
mv URL path uexport -> userexport
[friendica.git] / src / Util / Logger / StreamLogger.php
1 <?php
2
3 namespace Friendica\Util\Logger;
4
5 use Friendica\Util\DateTimeFormat;
6 use Friendica\Util\Introspection;
7 use Psr\Log\LogLevel;
8
9 /**
10  * A Logger instance for logging into a stream (file, stdout, stderr)
11  */
12 class StreamLogger extends AbstractLogger
13 {
14         /**
15          * The minimum loglevel at which this logger will be triggered
16          * @var string
17          */
18         private $logLevel;
19
20         /**
21          * The file URL of the stream (if needed)
22          * @var string
23          */
24         private $url;
25
26         /**
27          * The stream, where the current logger is writing into
28          * @var resource
29          */
30         private $stream;
31
32         /**
33          * The current process ID
34          * @var int
35          */
36         private $pid;
37
38         /**
39          * An error message
40          * @var string
41          */
42         private $errorMessage;
43
44         /**
45          * Translates LogLevel log levels to integer values
46          * @var array
47          */
48         private $levelToInt = [
49                 LogLevel::EMERGENCY => 0,
50                 LogLevel::ALERT     => 1,
51                 LogLevel::CRITICAL  => 2,
52                 LogLevel::ERROR     => 3,
53                 LogLevel::WARNING   => 4,
54                 LogLevel::NOTICE    => 5,
55                 LogLevel::INFO      => 6,
56                 LogLevel::DEBUG     => 7,
57         ];
58
59         /**
60          * {@inheritdoc}
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
63          *
64          * @throws \Exception
65          */
66         public function __construct($channel, $stream, Introspection $introspection, $level = LogLevel::DEBUG)
67         {
68                 parent::__construct($channel, $introspection);
69
70                 if (is_resource($stream)) {
71                         $this->stream = $stream;
72                 } elseif (is_string($stream)) {
73                         $this->url = $stream;
74                 } else {
75                         throw new \InvalidArgumentException('A stream must either be a resource or a string.');
76                 }
77
78                 $this->pid = getmypid();
79                 if (array_key_exists($level, $this->levelToInt)) {
80                         $this->logLevel = $this->levelToInt[$level];
81                 } else {
82                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
83                 }
84         }
85
86         public function close()
87         {
88                 if ($this->url && is_resource($this->stream)) {
89                         fclose($this->stream);
90                 }
91
92                 $this->stream = null;
93         }
94
95         /**
96          * Adds a new entry to the log
97          *
98          * @param int $level
99          * @param string $message
100          * @param array $context
101          *
102          * @return void
103          */
104         protected function addEntry($level, $message, $context = [])
105         {
106                 if (!array_key_exists($level, $this->levelToInt)) {
107                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
108                 }
109
110                 $logLevel = $this->levelToInt[$level];
111
112                 if ($logLevel > $this->logLevel) {
113                         return;
114                 }
115
116                 $this->checkStream();
117
118                 $formattedLog = $this->formatLog($level, $message, $context);
119                 fwrite($this->stream, $formattedLog);
120         }
121
122         /**
123          * Formats a log record for the syslog output
124          *
125          * @param int    $level   The loglevel/priority
126          * @param string $message The message
127          * @param array  $context The context of this call
128          *
129          * @return string the formatted syslog output
130          */
131         private function formatLog($level, $message, $context = [])
132         {
133                 $record = $this->introspection->getRecord();
134                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
135                 $logMessage = '';
136
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;
144
145                 return $logMessage;
146         }
147
148         private function checkStream()
149         {
150                 if (is_resource($this->stream)) {
151                         return;
152                 }
153
154                 if (empty($this->url)) {
155                         throw new \LogicException('Missing stream URL.');
156                 }
157
158                 $this->createDir();
159                 set_error_handler([$this, 'customErrorHandler']);
160                 $this->stream = fopen($this->url, 'ab');
161                 restore_error_handler();
162
163                 if (!is_resource($this->stream)) {
164                         $this->stream = null;
165
166                         throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
167                 }
168         }
169
170         private function createDir()
171         {
172                 $dirname = null;
173                 $pos = strpos($this->url, '://');
174                 if (!$pos) {
175                         $dirname = dirname($this->url);
176                 }
177
178                 if (substr($this->url, 0, 7) === 'file://') {
179                         $dirname = dirname(substr($this->url, 7));
180                 }
181
182                 if (isset($dirname) && !is_dir($dirname)) {
183                         set_error_handler([$this, 'customErrorHandler']);
184                         $status = mkdir($dirname, 0777, true);
185                         restore_error_handler();
186
187                         if (!$status && !is_dir($dirname)) {
188                                 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
189                         }
190                 }
191         }
192
193         private function customErrorHandler($code, $msg)
194         {
195                 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
196         }
197 }