From b78d9976386613e9d4764270c1635b51cd6237f3 Mon Sep 17 00:00:00 2001 From: Tarjei Huse Date: Sun, 27 Oct 2013 08:29:08 +0100 Subject: [PATCH] Add logging of exception line and file path to gelf message --- .../Formatter/GelfMessageFormatter.php | 7 +++++ .../Formatter/GelfMessageFormatterTest.php | 29 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/Monolog/Formatter/GelfMessageFormatter.php b/src/Monolog/Formatter/GelfMessageFormatter.php index aa01f491..6ebfaa7f 100644 --- a/src/Monolog/Formatter/GelfMessageFormatter.php +++ b/src/Monolog/Formatter/GelfMessageFormatter.php @@ -89,6 +89,13 @@ class GelfMessageFormatter extends NormalizerFormatter $message->setAdditional($this->contextPrefix . $key, is_scalar($val) ? $val : $this->toJson($val)); } + if (null === $message->getFile() && isset($record['context']['exception'])) { + if (preg_match("/^(.+):([0-9]+)$/", $record['context']['exception']['file'], $matches)) { + $message->setFile($matches[1]); + $message->setLine($matches[2]); + } + } + return $message; } } diff --git a/tests/Monolog/Formatter/GelfMessageFormatterTest.php b/tests/Monolog/Formatter/GelfMessageFormatterTest.php index a1db166a..068f1a49 100644 --- a/tests/Monolog/Formatter/GelfMessageFormatterTest.php +++ b/tests/Monolog/Formatter/GelfMessageFormatterTest.php @@ -119,6 +119,35 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase } + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testFormatWithContextContainingException() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger', 'exception' => [ + 'class' => '\Exception', + 'file' => '/some/file/in/dir.php:56', + 'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'] + ]), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log' + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $this->assertEquals("/some/file/in/dir.php", $message->getFile()); + $this->assertEquals("56", $message->getLine()); + + } + /** * @covers Monolog\Formatter\GelfMessageFormatter::format */