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