1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
namespace Lyal\MonologLogDNA; |
3
|
|
|
|
4
|
|
|
use Carbon\Carbon; |
5
|
|
|
use Monolog\Formatter\JsonFormatter; |
6
|
|
|
|
7
|
|
|
class LogDNAFormatter extends JsonFormatter |
8
|
|
|
{ |
9
|
|
|
private $carbon; |
10
|
|
|
private $environment; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* LogDNAFormatter constructor. |
14
|
|
|
* @param null $environment |
15
|
|
|
* @param bool|int $batchMode |
16
|
|
|
* @param bool $appendNewlines |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
public function __construct($environment = null, $batchMode = self::BATCH_MODE_NEWLINES, $appendNewlines = false) |
20
|
|
|
{ |
21
|
|
|
parent::__construct($batchMode, $appendNewlines); |
22
|
|
|
$this->carbon = new Carbon; |
23
|
|
|
$this->environment = $environment ?? getenv('APP_ENV') ?: 'unknown'; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Format a single record |
28
|
|
|
* |
29
|
|
|
* @param array $record |
30
|
|
|
* @return string |
31
|
|
|
*/ |
32
|
|
|
|
33
|
|
|
public function format(array $record) :string |
34
|
|
|
{ |
35
|
|
|
$payload = [ |
36
|
|
|
'lines' => [$this->formatLine($record)] |
37
|
|
|
]; |
38
|
|
|
return parent::format($payload); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Batch a group of records, returning |
44
|
|
|
* a json string |
45
|
|
|
* |
46
|
|
|
* @param array $records |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
|
|
|
50
|
|
|
public function formatBatch(array $records) |
51
|
|
|
{ |
52
|
|
|
$payload = ['lines' => []]; |
53
|
|
|
|
54
|
|
|
foreach ($records as $record) { |
55
|
|
|
$payload['lines'][] = $this->formatLine($record); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return json_encode($payload); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Helper function to format an individual log line for LogDNA |
63
|
|
|
* |
64
|
|
|
* @param array $record |
65
|
|
|
* @return array |
66
|
|
|
*/ |
67
|
|
|
|
68
|
|
|
private function formatLine(array $record) :array |
69
|
|
|
{ |
70
|
|
|
return [ |
71
|
|
|
'timestamp' => $this->carbon->getTimestamp(), |
72
|
|
|
'line' => $record['message'], |
73
|
|
|
'app' => $record['channel'], |
74
|
|
|
'level' => $record['level_name'], |
75
|
|
|
'env' => $this->environment, |
76
|
|
|
'meta' => $record['context'] |
77
|
|
|
]; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|