-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLogging.php
More file actions
300 lines (258 loc) · 9.83 KB
/
Logging.php
File metadata and controls
300 lines (258 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
declare(strict_types=1);
namespace ErrorHeroModule\Handler;
use ErrorException;
use ErrorHeroModule\Compat\Logger;
use ErrorHeroModule\Handler\Formatter\Json;
use ErrorHeroModule\Handler\Writer\Mail;
use ErrorHeroModule\HeroConstant;
use Laminas\Diactoros\Stream;
use Laminas\Http\Header\Cookie;
use Laminas\Http\PhpEnvironment\RemoteAddress;
use Laminas\Http\PhpEnvironment\Request as HttpRequest;
use Laminas\Log\Writer\Db;
use Laminas\Mail\Message;
use Laminas\Mail\Transport\TransportInterface;
use Laminas\Stdlib\ParametersInterface;
use Laminas\Stdlib\RequestInterface;
use RuntimeException;
use Throwable;
use Webmozart\Assert\Assert;
use function basename;
use function get_current_user;
use function getcwd;
use function implode;
use function php_uname;
use function str_replace;
use const PHP_BINARY;
use const PHP_EOL;
final class Logging
{
private array $configLoggingSettings = [];
private array $emailReceivers = [];
private readonly string $emailSender;
private const string PRIORITY = 'priority';
private const string ERROR_TYPE = 'errorType';
private const string ERROR_FILE = 'errorFile';
private const string ERROR_LINE = 'errorLine';
private const string TRACE = 'trace';
private const string ERROR_MESSAGE = 'errorMessage';
private const string SERVER_URL = 'server_url';
public function __construct(
private readonly Logger $logger,
array $errorHeroModuleLocalConfig,
private readonly array $logWritersConfig,
private readonly ?Message $message = null,
private readonly ?TransportInterface $mailMessageTransport = null,
private readonly bool $includeFilesToAttachments = true
) {
$this->configLoggingSettings = $errorHeroModuleLocalConfig['logging-settings'];
$this->emailReceivers = $errorHeroModuleLocalConfig['email-notification-settings']['email-to-send'];
$this->emailSender = $errorHeroModuleLocalConfig['email-notification-settings']['email-from'];
}
/**
* @return array<string, mixed>
*/
private function getRequestData(?RequestInterface $request): array
{
if (! $request instanceof HttpRequest) {
return [];
}
Assert::isInstanceOf($request, HttpRequest::class);
/** @var ParametersInterface $query */
$query = $request->getQuery();
/** @var ParametersInterface $post */
$post = $request->getPost();
/** @var ParametersInterface $files*/
$files = $request->getFiles();
$content = $request->getContent();
if ($content instanceof Stream) {
$content = (string) $content;
}
$queryData = $query->toArray();
$requestMethod = $request->getMethod();
$bodyData = $post->toArray();
$rawData = str_replace(PHP_EOL, '', $content);
$filesData = $this->includeFilesToAttachments
? $files->toArray()
: [];
$cookie = $request->getCookie();
$cookieData = $cookie instanceof Cookie
? $cookie->getArrayCopy()
: [];
$ipAddress = (new RemoteAddress())->getIpAddress();
return [
'request_method' => $requestMethod,
'query_data' => $queryData,
'body_data' => $bodyData,
'raw_data' => $rawData,
'files_data' => $filesData,
'cookie_data' => $cookieData,
'ip_address' => $ipAddress,
];
}
/**
* @return array{
* priority: int,
* errorType: string,
* errorFile: string,
* errorLine: int,
* trace: string,
* errorMessage: string
* }
*/
private function collectErrorExceptionData(Throwable $throwable): array
{
if (
$throwable instanceof ErrorException
&& isset(Logger::$errorPriorityMap[$severity = $throwable->getSeverity()])
) {
$priority = Logger::$errorPriorityMap[$severity];
$errorType = HeroConstant::ERROR_TYPE[$severity];
} else {
$priority = Logger::ERR;
$errorType = $throwable::class;
}
$errorFile = $throwable->getFile();
$errorLine = $throwable->getLine();
$traceAsString = $throwable->getTraceAsString();
$errorMessage = $throwable->getMessage();
return [
self::PRIORITY => $priority,
self::ERROR_TYPE => $errorType,
self::ERROR_FILE => $errorFile,
self::ERROR_LINE => $errorLine,
self::TRACE => $traceAsString,
self::ERROR_MESSAGE => $errorMessage,
];
}
/**
* @return array{
* server_url: string,
* url: string,
* file: string,
* line: int,
* error_type: string,
* trace: string,
* request_data: array<string, mixed>
* }
*/
private function collectErrorExceptionExtraData(array $collectedExceptionData, ?RequestInterface $request): array
{
if (! $request instanceof HttpRequest) {
$argv = $_SERVER['argv'] ?? [];
$serverUrl = php_uname('n');
$url = $serverUrl . ':' . basename((string) getcwd())
. ' ' . get_current_user()
. '$ ' . PHP_BINARY;
$params = implode(' ', $argv);
$url .= $params;
} else {
$http = $request->getUri();
$serverUrl = $http->getScheme() . '://' . $http->getHost();
$url = $http->toString();
}
return [
self::SERVER_URL => $serverUrl,
'url' => $url,
'file' => $collectedExceptionData[self::ERROR_FILE],
'line' => $collectedExceptionData[self::ERROR_LINE],
'error_type' => $collectedExceptionData[self::ERROR_TYPE],
self::TRACE => $collectedExceptionData[self::TRACE],
'request_data' => $this->getRequestData($request),
];
}
/**
* @throws RuntimeException When cannot connect to DB in the first place.
*/
private function isExists(
string $errorFile,
int $errorLine,
string $errorMessage,
string $url,
string $errorType
): bool {
$writers = $this->logger->getWriters()->toArray();
foreach ($writers as $writer) {
if ($writer instanceof Db) {
try {
$handlerWriterDb = new Writer\Checker\Db(
$writer,
$this->configLoggingSettings,
$this->logWritersConfig
);
if ($handlerWriterDb->isExists($errorFile, $errorLine, $errorMessage, $url, $errorType)) {
return true;
}
break;
} catch (RuntimeException $runtimeException) {
// use \Laminas\Db\Adapter\Exception\RuntimeException but do here
// to avoid too much deep trace from Laminas\Db classes
throw new ${! ${''} = $runtimeException::class}($runtimeException->getMessage());
}
}
}
return false;
}
private function sendMail(int $priority, string $errorMessage, array $extra, string $subject): void
{
if (! $this->message instanceof Message || ! $this->mailMessageTransport instanceof TransportInterface) {
return;
}
if ($this->emailReceivers === []) {
return;
}
$this->message->setFrom($this->emailSender);
$this->message->setSubject($subject);
$filesData = $extra['request_data']['files_data'] ?? [];
foreach ($this->emailReceivers as $emailReceiver) {
$this->message->setTo($emailReceiver);
$writer = new Mail(
$this->message,
$this->mailMessageTransport,
$filesData
);
$writer->setFormatter(new Json());
(new Logger())->addWriter($writer)
->log($priority, $errorMessage, $extra);
}
}
public function handleErrorException(Throwable $throwable, ?RequestInterface $request = null): void
{
$collectedExceptionData = $this->collectErrorExceptionData($throwable);
/**
* @var array{url: string, server_url: string, mixed} $extra
*/
$extra = $this->collectErrorExceptionExtraData($collectedExceptionData, $request);
$serverUrl = $extra[self::SERVER_URL];
try {
if (
$this->isExists(
$collectedExceptionData[self::ERROR_FILE],
$collectedExceptionData[self::ERROR_LINE],
$collectedExceptionData[self::ERROR_MESSAGE],
$extra['url'],
$collectedExceptionData[self::ERROR_TYPE]
)
) {
return;
}
unset($extra[self::SERVER_URL]);
$this->logger->log(
$collectedExceptionData[self::PRIORITY],
$collectedExceptionData[self::ERROR_MESSAGE],
$extra
);
} catch (RuntimeException $runtimeException) {
$collectedExceptionData = $this->collectErrorExceptionData($runtimeException);
$extra = $this->collectErrorExceptionExtraData($collectedExceptionData, $request);
unset($extra[self::SERVER_URL]);
}
$this->sendMail(
$collectedExceptionData[self::PRIORITY],
$collectedExceptionData[self::ERROR_MESSAGE],
$extra,
'[' . $serverUrl . '] ' . $collectedExceptionData[self::ERROR_TYPE] . ' has thrown'
);
}
}