-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogHandler.php
More file actions
82 lines (69 loc) · 2.46 KB
/
LogHandler.php
File metadata and controls
82 lines (69 loc) · 2.46 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
<?php
namespace TransformStudios\Front\Logging;
use Illuminate\Support\Collection;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\Logger as Monolog;
use Monolog\LogRecord;
use Statamic\Support\Arr;
use Statamic\Support\Str;
use Throwable;
class LogHandler extends AbstractProcessingHandler
{
/** @throws \Illuminate\Contracts\Container\BindingResolutionException */
public function __construct(array $channelConfig)
{
parent::__construct(Monolog::toMonologLevel($channelConfig['level'] ?? Level::Debug));
}
public function write(array|LogRecord $record): void
{
if (! $conversation = config('front.logging.conversation_id')) {
return;
}
if ($record instanceof LogRecord) {
$record = $record->toArray();
}
if (! Arr::get($record, 'context.exception')) {
$errors = collect([
'Request URL: '.request()->fullUrl(),
'Request data: '.json_encode(request()->input()),
'Error: '.json_encode($record),
]);
front()
->post(
"/conversations/$conversation/comments",
['body' => Str::limit($errors->implode(PHP_EOL), 10000)]
)->throw();
return;
}
front()
->post(
"/conversations/$conversation/comments",
$this->convertErrorToFrontMessage(Arr::get($record, 'context.exception'))
)->throw();
}
private function convertErrorToFrontMessage(Throwable $error): array
{
return ['body' => $this->formatErrorLines($error)->implode(PHP_EOL)];
}
private function formatErrorLines(Throwable $error): Collection
{
return collect([
'Request URL: '.request()->fullUrl(),
'Request data: '.json_encode(request()->input()),
'**'.$error->getMessage().'**',
'* '.$error->getFile().' ('.$error->getLine().')',
])->merge($this->formatStackTrace($error));
}
private function formatStackTrace(Throwable $error): Collection
{
return collect($error->getTrace())
->take(10)
->map(function (array $traceItem) {
if (! $file = Arr::get($traceItem, 'file')) {
return '* '.json_encode($traceItem);
}
return '* '.$file.' ('.Arr::get($traceItem, 'line').')';
});
}
}