1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-07-31 10:20:14 +02:00

Added 'timestamp' parameter to $record for indexing by Loggly

This commit is contained in:
Adam Pancutt
2014-01-22 14:31:31 +00:00
parent b748794bba
commit a46413b15b
3 changed files with 91 additions and 2 deletions

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
/**
* Encodes message information into JSON in a format compatible with Loggly.
*
* @author Adam Pancutt <adam@pancutt.com>
*/
class LogglyFormatter extends JsonFormatter
{
/**
* Overrides the default batch mode to new lines for compatibility with the
* Loggly bulk API.
*
* @param integer $batch_mode
*/
public function __construct($batch_mode = self::BATCH_MODE_NEWLINES)
{
parent::__construct($batch_mode);
}
/**
* Appends the 'timestamp' parameter for indexing by Loggly.
*
* @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format()
*/
public function format(array $record)
{
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
$record["timestamp"] = $record["datetime"]->format("c");
// @todo unset the 'datetime' parameter, retained for BC
}
return parent::format($record);
}
}

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
use Monolog\Formatter\LogglyFormatter;
/**
* Sends errors to Loggly.
@@ -88,6 +88,6 @@ class LogglyHandler extends AbstractProcessingHandler
protected function getDefaultFormatter()
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
return new LogglyFormatter();
}
}

View File

@@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Logger;
use Monolog\TestCase;
class LogglyFormatterTest extends TestCase
{
/**
* @covers Monolog\Formatter\LogglyFormatter::__construct
*/
public function testConstruct()
{
$formatter = new LogglyFormatter();
$this->assertEquals(LogglyFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
$formatter = new LogglyFormatter(LogglyFormatter::BATCH_MODE_JSON);
$this->assertEquals(LogglyFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
}
/**
* @covers Monolog\Formatter\LogglyFormatter::format
*/
public function testFormat()
{
$formatter = new LogglyFormatter();
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
$this->assertArrayHasKey("timestamp", $formatted_decoded);
$this->assertEquals(new \DateTime($formatted_decoded["timestamp"]), $record["datetime"]);
}
}