-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathElasticCommonSchemaFormatter.php
More file actions
213 lines (178 loc) · 6.59 KB
/
ElasticCommonSchemaFormatter.php
File metadata and controls
213 lines (178 loc) · 6.59 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
<?php
declare(strict_types=1);
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
namespace Elastic\Monolog\Formatter;
use Elastic\Types\Error as EcsError;
use Monolog\Formatter\NormalizerFormatter;
use Throwable;
/**
* Serializes a log message to the Elastic Common Schema (ECS)
*
* @version Monolog v2.x
* @version ECS v1.x
*
* @see https://www.elastic.co/guide/en/ecs/1.4/ecs-log.html
* @see \Elastic\Tests\Monolog\Formatter\ElasticCommonSchemaFormatterTest
*
* @author Philip Krauss <philip.krauss@elastic.co>
*/
class ElasticCommonSchemaFormatter extends NormalizerFormatter
{
private const ECS_VERSION = '1.2.0';
private static $logOriginKeys = ['file' => true, 'line' => true, 'class' => true, 'function' => true, 'callType' => true];
/**
* @var array
*
* @link https://www.elastic.co/guide/en/ecs/current/ecs-base.html
*/
protected $tags;
/** @var bool */
protected $useLogOriginFromContext = true;
/**
* @param array $tags optional tags to enrich the log lines
*/
public function __construct(array $tags = [])
{
parent::__construct('Y-m-d\TH:i:s.uP');
$this->tags = $tags;
}
public function useLogOriginFromContext(bool $useLogOriginFromContext): self
{
$this->useLogOriginFromContext = $useLogOriginFromContext;
return $this;
}
/** @inheritDoc */
protected function normalize($data, int $depth = 0)
{
if ($depth > $this->maxNormalizeDepth) {
return parent::normalize($data, $depth);
}
if ($data instanceof Throwable) {
return EcsError::serialize($data);
}
if ($data instanceof EcsError) {
return $data->jsonSerialize();
}
return parent::normalize($data, $depth);
}
/**
* {@inheritdoc}
*
* @link https://www.elastic.co/guide/en/ecs/1.1/ecs-log.html
* @link https://www.elastic.co/guide/en/ecs/1.1/ecs-base.html
* @link https://www.elastic.co/guide/en/ecs/current/ecs-tracing.html
*/
public function format(array $record): string
{
$inRecord = $this->normalize($record);
// Build Skeleton with "@timestamp" and "log.level"
$outRecord = [
'@timestamp' => $inRecord['datetime'],
'log.level' => $inRecord['level_name'],
];
// Add "message"
if (isset($inRecord['message']) === true) {
$outRecord['message'] = $inRecord['message'];
}
// Add "ecs.version"
$outRecord['ecs.version'] = self::ECS_VERSION;
// Add "log": { "logger": ..., ... }
$outRecord['log'] = [
'logger' => $inRecord['channel'],
];
// Add Tracing Context
if (isset($inRecord['context']['tracing']['Elastic\Types\Tracing']) === true) {
$outRecord += $inRecord['context']['tracing']['Elastic\Types\Tracing'];
unset($inRecord['context']['tracing']);
}
// Add Service Context
if (isset($inRecord['context']['service']['Elastic\Types\Service']) === true) {
$outRecord += $inRecord['context']['service']['Elastic\Types\Service'];
unset($inRecord['context']['service']);
}
// Add User Context
if (isset($inRecord['context']['user']['Elastic\Types\User']) === true) {
$outRecord += $inRecord['context']['user']['Elastic\Types\User'];
unset($inRecord['context']['user']);
}
$this->formatContext($inRecord['extra'], /* ref */ $outRecord);
$this->formatContext($inRecord['context'], /* ref */ $outRecord);
// Add ECS Tags
if (empty($this->tags) === false) {
$outRecord['tags'] = $this->normalize($this->tags);
}
return $this->toJson($outRecord) . "\n";
}
private function formatContext(array $inContext, array &$outRecord): void
{
$foundLogOriginKeys = false;
// Context should go to the top of the out record
foreach ($inContext as $contextKey => $contextVal) {
// label keys should be sanitized
if ($contextKey === 'labels') {
$outLabels = [];
foreach ($contextVal as $labelKey => $labelVal) {
$outLabels[str_replace(['.', ' ', '*', '\\'], '_', trim($labelKey))] = $labelVal;
}
$outRecord['labels'] = $outLabels;
continue;
}
if ($this->useLogOriginFromContext) {
if (isset(self::$logOriginKeys[$contextKey])) {
$foundLogOriginKeys = true;
continue;
}
}
$outRecord[$contextKey] = $contextVal;
}
if ($foundLogOriginKeys) {
$this->formatLogOrigin($inContext, /* ref */ $outRecord);
}
}
private function formatLogOrigin(array $inContext, array &$outRecord): void
{
$originVal = [];
$fileVal = [];
if (array_key_exists('file', $inContext)) {
$fileName = $inContext['file'];
if (is_string($fileName)) {
$fileVal['name'] = $fileName;
}
}
if (array_key_exists('line', $inContext)) {
$fileLine = $inContext['line'];
if (is_int($fileLine)) {
$fileVal['line'] = $fileLine;
}
}
if (!empty($fileVal)) {
$originVal['file'] = $fileVal;
}
$outFunctionVal = null;
if (array_key_exists('function', $inContext)) {
$inFunctionVal = $inContext['function'];
if (is_string($inFunctionVal)) {
if (array_key_exists('class', $inContext)) {
$inClassVal = $inContext['class'];
if (is_string($inClassVal)) {
$callType = array_key_exists('callType', $inContext) && is_string($inContext['callType'])
? $inContext['callType']
: '::';
$outFunctionVal = $inClassVal . $callType . $inFunctionVal;
}
}
if ($outFunctionVal === null) {
$outFunctionVal = $inFunctionVal;
}
}
}
if ($outFunctionVal !== null) {
$originVal['function'] = $outFunctionVal;
}
if (!empty($originVal)) {
$outRecord['log']['origin'] = $originVal;
}
}
}