]> git.mxchange.org Git - friendica.git/blob - src/Util/Logger/StreamLogger.php
ad1b152d9e117c5f2fe098db86e9c12b6a67db2c
[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 AbstractFriendicaLogger
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          * Translates LogLevel log levels to integer values
40          * @var array
41          */
42         private $levelToInt = [
43                 LogLevel::EMERGENCY => 0,
44                 LogLevel::ALERT     => 1,
45                 LogLevel::CRITICAL  => 2,
46                 LogLevel::ERROR     => 3,
47                 LogLevel::WARNING   => 4,
48                 LogLevel::NOTICE    => 5,
49                 LogLevel::INFO      => 6,
50                 LogLevel::DEBUG     => 7,
51         ];
52
53         /**
54          * {@inheritdoc}
55          * @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
56          * @param string          $level  The minimum loglevel at which this logger will be triggered
57          *
58          * @throws \Exception
59          */
60         public function __construct($channel, $stream, Introspection $introspection, $level = LogLevel::DEBUG)
61         {
62                 parent::__construct($channel, $introspection);
63
64                 if (is_resource($stream)) {
65                         $this->stream = $stream;
66                 } elseif (is_string($stream)) {
67                         $this->url = $stream;
68                 } else {
69                         throw new \InvalidArgumentException('A stream must either be a resource or a string.');
70                 }
71
72                 $this->pid = getmypid();
73                 if (array_key_exists($level, $this->levelToInt)) {
74                         $this->logLevel = $this->levelToInt[$level];
75                 } else {
76                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
77                 }
78         }
79
80         public function close()
81         {
82                 if ($this->url && is_resource($this->stream)) {
83                         fclose($this->stream);
84                 }
85
86                 $this->stream = null;
87         }
88
89         /**
90          * Adds a new entry to the log
91          *
92          * @param int $level
93          * @param string $message
94          * @param array $context
95          *
96          * @return void
97          */
98         protected function addEntry($level, $message, $context = [])
99         {
100                 if (!array_key_exists($level, $this->levelToInt)) {
101                         throw new \InvalidArgumentException('The level "%s" is not valid', $level);
102                 }
103
104                 $logLevel = $this->levelToInt[$level];
105
106                 if ($logLevel > $this->logLevel) {
107                         return;
108                 }
109
110                 $this->checkStream();
111
112                 $this->stream = fopen($this->url, 'a');
113                 $formattedLog = $this->formatLog($level, $message, $context);
114                 fwrite($this->stream, $formattedLog);
115         }
116
117         /**
118          * Formats a log record for the syslog output
119          *
120          * @param int    $level   The loglevel/priority
121          * @param string $message The message
122          * @param array  $context The context of this call
123          *
124          * @return string the formatted syslog output
125          */
126         private function formatLog($level, $message, $context = [])
127         {
128                 $record = $this->introspection->getRecord();
129                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
130                 $logMessage = '';
131
132                 $logMessage .= DateTimeFormat::localNow() . ' ';
133                 $logMessage .= $this->channel . ' ';
134                 $logMessage .= '[' . strtoupper($level) . ']: ';
135                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
136                 $logMessage .= @json_encode($context) . ' - ';
137                 $logMessage .= @json_encode($record);
138                 $logMessage .= PHP_EOL;
139
140                 return $logMessage;
141         }
142
143         private function checkStream()
144         {
145                 if (is_resource($this->stream)) {
146                         return;
147                 }
148
149                 if (empty($this->url)) {
150                         throw new \LogicException('Missing stream URL.');
151                 }
152
153                 $this->createDir();
154                 $this->stream = fopen($this->url, 'a');
155
156                 if (!is_resource($this->stream)) {
157                         $this->stream = null;
158
159                         throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened.', $this->url));
160                 }
161         }
162
163         private function createDir()
164         {
165                 $dirname = null;
166                 $pos = strpos($this->url, '://');
167                 if (!$pos) {
168                         $dirname = dirname($this->url);
169                 }
170
171                 if (substr($this->url, 0, 7) === 'file://') {
172                         $dirname = dirname(substr($this->url, 7));
173                 }
174
175                 if (isset($dirname) && !is_dir($dirname)) {
176                         $status = mkdir($dirname, 0777, true);
177                         if (!$status && !is_dir($dirname)) {
178                                 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created.', $dirname));
179                         }
180                 }
181         }
182 }