Skip to content

Commit 131663b

Browse files
authored
Merge pull request #2 from philkra/dedot-labels-key
sanitize labels issue #1
2 parents b8f51de + f21e99a commit 131663b

3 files changed

Lines changed: 40 additions & 2 deletions

File tree

src/Elastic/Monolog/Formatter/ElasticCommonSchemaFormatter.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,10 @@ public function format(array $record): string
8787

8888
// Add ECS Labels
8989
if (empty($record['context']) === false) {
90-
$message['labels'] = $record['context'];
90+
$message['labels'] = [];
91+
foreach ($record['context'] as $key => $val) {
92+
$message['labels'][str_replace(['.', ' '], '_', trim($key))] = $val;
93+
}
9194
}
9295

9396
// Add ECS Tags

tests/Elastic/BaseTestCase.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,4 @@ protected function generateException() : Throwable
4141
{
4242
return new InvalidArgumentException('This is a InvalidArgumentException', 42);
4343
}
44-
4544
}

tests/Elastic/Monolog/Formatter/ElasticCommonSchemaFormatterTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,4 +246,40 @@ public function testNormalizeException()
246246
$this->assertArrayNotHasKey('labels', $decoded);
247247
}
248248

249+
/**
250+
* @depends testFormat
251+
*
252+
* @covers Elastic\Monolog\Formatter\ElasticCommonSchemaFormatter::__construct
253+
* @covers Elastic\Monolog\Formatter\ElasticCommonSchemaFormatter::format
254+
*/
255+
public function testSanitizeOfLabelKeys()
256+
{
257+
$msg = [
258+
'level' => Logger::NOTICE,
259+
'level_name' => 'NOTICE',
260+
'channel' => 'ecs',
261+
'datetime' => new \DateTimeImmutable("@0"),
262+
'message' => md5(uniqid()),
263+
'context' => [
264+
'sim ple' => 'sim_ple',
265+
' lpad' => 'lpad',
266+
'rpad ' => 'rpad',
267+
'foo.bar' => 'foo_bar',
268+
'a.b.c' => 'a_b_c',
269+
'.hello' => '_hello',
270+
'lorem.' => 'lorem_',
271+
],
272+
'extra' => [],
273+
];
274+
275+
$formatter = new ElasticCommonSchemaFormatter();
276+
$doc = $formatter->format($msg);
277+
$decoded = json_decode($doc, true);
278+
279+
$this->assertArrayHasKey('labels', $decoded);
280+
foreach ($msg['context'] as $keyPrevious => $keySanitized) {
281+
$this->assertArrayNotHasKey($keyPrevious, $decoded['labels'], $keyPrevious);
282+
$this->assertArrayHasKey($keySanitized, $decoded['labels'], $keySanitized);
283+
}
284+
}
249285
}

0 commit comments

Comments
 (0)