]> git.mxchange.org Git - friendica.git/blob - src/Util/Logger/StreamLogger.php
wrapping up 2019.12
[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\FileSystem;
7 use Friendica\Util\Introspection;
8 use Psr\Log\LogLevel;
9
10 /**
11  * A Logger instance for logging into a stream (file, stdout, stderr)
12  */
13 class StreamLogger extends AbstractLogger
14 {
15         /**
16          * The minimum loglevel at which this logger will be triggered
17          * @var string
18          */
19         private $logLevel;
20
21         /**
22          * The file URL of the stream (if needed)
23          * @var string
24          */
25         private $url;
26
27         /**
28          * The stream, where the current logger is writing into
29          * @var resource
30          */
31         private $stream;
32
33         /**
34          * The current process ID
35          * @var int
36          */
37         private $pid;
38
39         /**
40          * @var FileSystem
41          */
42         private $fileSystem;
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, FileSystem $fileSystem, $level = LogLevel::DEBUG)
67         {
68                 $this->fileSystem = $fileSystem;
69
70                 parent::__construct($channel, $introspection);
71
72                 if (is_resource($stream)) {
73                         $this->stream = $stream;
74                 } elseif (is_string($stream)) {
75                         $this->url = $stream;
76                 } else {
77                         throw new \InvalidArgumentException('A stream must either be a resource or a string.');
78                 }
79
80                 $this->pid = getmypid();
81                 if (array_key_exists($level, $this->levelToInt)) {
82                         $this->logLevel = $this->levelToInt[$level];
83                 } else {
84                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
85                 }
86
87                 $this->checkStream();
88         }
89
90         public function close()
91         {
92                 if ($this->url && is_resource($this->stream)) {
93                         fclose($this->stream);
94                 }
95
96                 $this->stream = null;
97         }
98
99         /**
100          * Adds a new entry to the log
101          *
102          * @param int $level
103          * @param string $message
104          * @param array $context
105          *
106          * @return void
107          */
108         protected function addEntry($level, $message, $context = [])
109         {
110                 if (!array_key_exists($level, $this->levelToInt)) {
111                         throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
112                 }
113
114                 $logLevel = $this->levelToInt[$level];
115
116                 if ($logLevel > $this->logLevel) {
117                         return;
118                 }
119
120                 $this->checkStream();
121
122                 $formattedLog = $this->formatLog($level, $message, $context);
123                 fwrite($this->stream, $formattedLog);
124         }
125
126         /**
127          * Formats a log record for the syslog output
128          *
129          * @param int    $level   The loglevel/priority
130          * @param string $message The message
131          * @param array  $context The context of this call
132          *
133          * @return string the formatted syslog output
134          */
135         private function formatLog($level, $message, $context = [])
136         {
137                 $record = $this->introspection->getRecord();
138                 $record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
139                 $logMessage = '';
140
141                 $logMessage .= DateTimeFormat::utcNow() . ' ';
142                 $logMessage .= $this->channel . ' ';
143                 $logMessage .= '[' . strtoupper($level) . ']: ';
144                 $logMessage .= $this->psrInterpolate($message, $context) . ' ';
145                 $logMessage .= @json_encode($context) . ' - ';
146                 $logMessage .= @json_encode($record);
147                 $logMessage .= PHP_EOL;
148
149                 return $logMessage;
150         }
151
152         private function checkStream()
153         {
154                 if (is_resource($this->stream)) {
155                         return;
156                 }
157
158                 if (empty($this->url)) {
159                         throw new \LogicException('Missing stream URL.');
160                 }
161
162                 $this->stream = $this->fileSystem->createStream($this->url);
163         }
164 }