update 1.0.8.0

Commits for version update
This commit is contained in:
Manish Verma
2016-10-17 12:02:27 +05:30
parent dec927987b
commit 76e85db070
9674 changed files with 495757 additions and 58922 deletions

View File

@@ -1,3 +1,21 @@
### 1.21.0 (2016-07-29)
* Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues
* Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order
* Added ability to format the main line of text the SlackHandler sends by explictly setting a formatter on the handler
* Added information about SoapFault instances in NormalizerFormatter
* Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level
### 1.20.0 (2016-07-02)
* Added FingersCrossedHandler::activate() to manually trigger the handler regardless of the activation policy
* Added StreamHandler::getUrl to retrieve the stream's URL
* Added ability to override addRow/addTitle in HtmlFormatter
* Added the $context to context information when the ErrorHandler handles a regular php error
* Deprecated RotatingFileHandler::setFilenameFormat to only support 3 formats: Y, Y-m and Y-m-d
* Fixed WhatFailureGroupHandler to work with PHP7 throwables
* Fixed a few minor bugs
### 1.19.0 (2016-04-12)
* Break: StreamHandler will not close streams automatically that it does not own. If you pass in a stream (not a path/url), then it will not close it for you. You can retrieve those using getStream() if needed

View File

@@ -19,7 +19,7 @@
"require-dev": {
"phpunit/phpunit": "~4.5",
"graylog2/gelf-php": "~1.0",
"raven/raven": "^0.13",
"sentry/sentry": "^0.13",
"ruflin/elastica": ">=0.90 <3.0",
"doctrine/couchdb": "~1.0@dev",
"aws/aws-sdk-php": "^2.4.9",
@@ -32,7 +32,7 @@
"_": "phpunit/phpunit-mock-objects required in 2.3.0 due to https://github.com/sebastianbergmann/phpunit-mock-objects/issues/223 - needs hhvm 3.8+ on travis",
"suggest": {
"graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
"raven/raven": "Allow sending log messages to a Sentry server",
"sentry/sentry": "Allow sending log messages to a Sentry server",
"doctrine/couchdb": "Allow sending log messages to a CouchDB server",
"ruflin/elastica": "Allow sending log messages to an Elastic Search server",
"php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",

View File

@@ -33,6 +33,7 @@ class ErrorHandler
private $previousErrorHandler;
private $errorLevelMap;
private $handleOnlyReportedErrors;
private $hasFatalErrorHandler;
private $fatalLevel;
@@ -80,13 +81,15 @@ class ErrorHandler
}
}
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true)
{
$prev = set_error_handler(array($this, 'handleError'), $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true;
}
$this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
}
public function registerFatalHandler($level = null, $reservedMemorySize = 20)
@@ -142,7 +145,7 @@ class ErrorHandler
*/
public function handleError($code, $message, $file = '', $line = 0, $context = array())
{
if (!(error_reporting() & $code)) {
if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) {
return;
}

View File

@@ -106,7 +106,7 @@ class GelfMessageFormatter extends NormalizerFormatter
}
foreach ($record['extra'] as $key => $val) {
$val = is_scalar($val) ? $val : $this->toJson($val);
$val = is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len += strlen($this->extraPrefix . $key . $val);
if ($len > self::MAX_LENGTH) {
$message->setAdditional($this->extraPrefix . $key, substr($val, 0, self::MAX_LENGTH - $len));
@@ -116,7 +116,7 @@ class GelfMessageFormatter extends NormalizerFormatter
}
foreach ($record['context'] as $key => $val) {
$val = is_scalar($val) ? $val : $this->toJson($val);
$val = is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len += strlen($this->contextPrefix . $key . $val);
if ($len > self::MAX_LENGTH) {
$message->setAdditional($this->contextPrefix . $key, substr($val, 0, self::MAX_LENGTH - $len));

View File

@@ -51,7 +51,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param bool $escapeTd false if td content must not be html escaped
* @return string
*/
private function addRow($th, $td = ' ', $escapeTd = true)
protected function addRow($th, $td = ' ', $escapeTd = true)
{
$th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
if ($escapeTd) {
@@ -68,7 +68,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param int $level Error level
* @return string
*/
private function addTitle($title, $level)
protected function addTitle($title, $level)
{
$title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');

View File

@@ -186,6 +186,9 @@ class JsonFormatter extends NormalizerFormatter
foreach ($trace as $frame) {
if (isset($frame['file'])) {
$data['trace'][] = $frame['file'].':'.$frame['line'];
} elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
// We should again normalize the frames, because it might contain invalid items
$data['trace'][] = $frame['function'];
} else {
// We should again normalize the frames, because it might contain invalid items
$data['trace'][] = $this->normalize($frame);

View File

@@ -127,10 +127,27 @@ class NormalizerFormatter implements FormatterInterface
'file' => $e->getFile().':'.$e->getLine(),
);
if ($e instanceof \SoapFault) {
if (isset($e->faultcode)) {
$data['faultcode'] = $e->faultcode;
}
if (isset($e->faultactor)) {
$data['faultactor'] = $e->faultactor;
}
if (isset($e->detail)) {
$data['detail'] = $e->detail;
}
}
$trace = $e->getTrace();
foreach ($trace as $frame) {
if (isset($frame['file'])) {
$data['trace'][] = $frame['file'].':'.$frame['line'];
} elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
// We should again normalize the frames, because it might contain invalid items
$data['trace'][] = $frame['function'];
} else {
// We should again normalize the frames, because it might contain invalid items
$data['trace'][] = $this->toJson($this->normalize($frame), true);
@@ -185,7 +202,7 @@ class NormalizerFormatter implements FormatterInterface
* Handle a json_encode failure.
*
* If the failure is due to invalid string encoding, try to clean the
* input and encode again. If the second encoding iattempt fails, the
* input and encode again. If the second encoding attempt fails, the
* inital error is not encoding related or the input can't be cleaned then
* raise a descriptive exception.
*

View File

@@ -169,6 +169,8 @@ abstract class AbstractHandler implements HandlerInterface
$this->close();
} catch (\Exception $e) {
// do nothing
} catch (\Throwable $e) {
// do nothing
}
}

View File

@@ -79,6 +79,26 @@ class FingersCrossedHandler extends AbstractHandler
return true;
}
/**
* Manually activate this logger regardless of the activation strategy
*/
public function activate()
{
if ($this->stopBuffering) {
$this->buffering = false;
}
if (!$this->handler instanceof HandlerInterface) {
$record = end($this->buffer) ?: null;
$this->handler = call_user_func($this->handler, $record, $this);
if (!$this->handler instanceof HandlerInterface) {
throw new \RuntimeException("The factory callable should return a HandlerInterface");
}
}
$this->handler->handleBatch($this->buffer);
$this->buffer = array();
}
/**
* {@inheritdoc}
*/
@@ -96,17 +116,7 @@ class FingersCrossedHandler extends AbstractHandler
array_shift($this->buffer);
}
if ($this->activationStrategy->isHandlerActivated($record)) {
if ($this->stopBuffering) {
$this->buffering = false;
}
if (!$this->handler instanceof HandlerInterface) {
$this->handler = call_user_func($this->handler, $record, $this);
if (!$this->handler instanceof HandlerInterface) {
throw new \RuntimeException("The factory callable should return a HandlerInterface");
}
}
$this->handler->handleBatch($this->buffer);
$this->buffer = array();
$this->activate();
}
} else {
$this->handler->handle($record);

View File

@@ -75,6 +75,16 @@ class GroupHandler extends AbstractHandler
*/
public function handleBatch(array $records)
{
if ($this->processors) {
$processed = array();
foreach ($records as $record) {
foreach ($this->processors as $processor) {
$processed[] = call_user_func($processor, $record);
}
}
$records = $processed;
}
foreach ($this->handlers as $handler) {
$handler->handleBatch($records);
}

View File

@@ -33,7 +33,7 @@ class HandlerWrapper implements HandlerInterface
/**
* @var HandlerInterface
*/
private $handler;
protected $handler;
/**
* HandlerWrapper constructor.

View File

@@ -91,23 +91,27 @@ class NewRelicHandler extends AbstractProcessingHandler
newrelic_notice_error($record['message']);
}
foreach ($record['formatted']['context'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue);
if (isset($record['formatted']['context']) && is_array($record['formatted']['context'])) {
foreach ($record['formatted']['context'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue);
}
} else {
$this->setNewRelicParameter('context_' . $key, $parameter);
}
} else {
$this->setNewRelicParameter('context_' . $key, $parameter);
}
}
foreach ($record['formatted']['extra'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue);
if (isset($record['formatted']['extra']) && is_array($record['formatted']['extra'])) {
foreach ($record['formatted']['extra'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue);
}
} else {
$this->setNewRelicParameter('extra_' . $key, $parameter);
}
} else {
$this->setNewRelicParameter('extra_' . $key, $parameter);
}
}
}

View File

@@ -24,6 +24,10 @@ use Monolog\Logger;
*/
class RotatingFileHandler extends StreamHandler
{
const FILE_PER_DAY = 'Y-m-d';
const FILE_PER_MONTH = 'Y-m';
const FILE_PER_YEAR = 'Y';
protected $filename;
protected $maxFiles;
protected $mustRotate;
@@ -64,6 +68,21 @@ class RotatingFileHandler extends StreamHandler
public function setFilenameFormat($filenameFormat, $dateFormat)
{
if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
trigger_error(
'Invalid date format - format must be one of '.
'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
'date formats using slashes, underscores and/or dots instead of dashes.',
E_USER_DEPRECATED
);
}
if (substr_count($filenameFormat, '{date}') === 0) {
trigger_error(
'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.',
E_USER_DEPRECATED
);
}
$this->filenameFormat = $filenameFormat;
$this->dateFormat = $dateFormat;
$this->url = $this->getTimedFilename();

View File

@@ -144,19 +144,25 @@ class SlackHandler extends SocketHandler
'attachments' => array(),
);
if ($this->formatter) {
$message = $this->formatter->format($record);
} else {
$message = $record['message'];
}
if ($this->useAttachment) {
$attachment = array(
'fallback' => $record['message'],
'fallback' => $message,
'color' => $this->getAttachmentColor($record['level']),
'fields' => array(),
);
if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name'];
$attachment['text'] = $record['message'];
$attachment['text'] = $message;
} else {
$attachment['title'] = 'Message';
$attachment['text'] = $record['message'];
$attachment['text'] = $message;
$attachment['fields'][] = array(
'title' => 'Level',
'value' => $record['level_name'],
@@ -206,7 +212,7 @@ class SlackHandler extends SocketHandler
$dataArray['attachments'] = json_encode(array($attachment));
} else {
$dataArray['text'] = $record['message'];
$dataArray['text'] = $message;
}
if ($this->iconEmoji) {

View File

@@ -75,13 +75,23 @@ class StreamHandler extends AbstractProcessingHandler
return $this->stream;
}
/**
* Return the stream URL if it was configured with a URL and not an active resource
*
* @return string|null
*/
public function getUrl()
{
return $this->url;
}
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
if (!is_resource($this->stream)) {
if (!$this->url) {
if (null === $this->url || '' === $this->url) {
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
}
$this->createDir();

View File

@@ -35,6 +35,8 @@ class WhatFailureGroupHandler extends GroupHandler
$handler->handle($record);
} catch (\Exception $e) {
// What failure?
} catch (\Throwable $e) {
// What failure?
}
}
@@ -51,6 +53,8 @@ class WhatFailureGroupHandler extends GroupHandler
$handler->handleBatch($records);
} catch (\Exception $e) {
// What failure?
} catch (\Throwable $e) {
// What failure?
}
}
}

View File

@@ -85,6 +85,33 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
), $formatted);
}
public function testFormatSoapFaultException()
{
if (!class_exists('SoapFault')) {
$this->markTestSkipped('Requires the soap extension');
}
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', 'world');
$formatted = $formatter->format(array(
'exception' => $e,
));
unset($formatted['exception']['trace']);
$this->assertEquals(array(
'exception' => array(
'class' => 'SoapFault',
'message' => 'bar',
'code' => 0,
'file' => $e->getFile().':'.$e->getLine(),
'faultcode' => 'foo',
'faultactor' => 'hello',
'detail' => 'world',
),
), $formatted);
}
public function testFormatToStringExceptionHandle()
{
$formatter = new NormalizerFormatter('Y-m-d');

View File

@@ -22,6 +22,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleBuffers()
{
@@ -39,6 +40,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleStopsBufferingAfterTrigger()
{
@@ -53,6 +55,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
* @covers Monolog\Handler\FingersCrossedHandler::reset
*/
public function testHandleRestartBufferingAfterReset()
@@ -71,6 +74,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleRestartBufferingAfterBeingTriggeredWhenStopBufferingIsDisabled()
{
@@ -87,6 +91,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleBufferLimit()
{
@@ -103,6 +108,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleWithCallback()
{
@@ -121,6 +127,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
* @expectedException RuntimeException
*/
public function testHandleWithBadCallbackThrowsException()
@@ -173,6 +180,22 @@ class FingersCrossedHandlerTest extends TestCase
$this->assertTrue($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testOverrideActivationStrategy()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning'));
$handler->handle($this->getRecord(Logger::DEBUG));
$this->assertFalse($test->hasDebugRecords());
$handler->activate();
$this->assertTrue($test->hasDebugRecords());
$handler->handle($this->getRecord(Logger::INFO));
$this->assertTrue($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated
@@ -209,6 +232,7 @@ class FingersCrossedHandlerTest extends TestCase
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleUsesProcessors()
{

View File

@@ -86,4 +86,27 @@ class GroupHandlerTest extends TestCase
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\GroupHandler::handle
*/
public function testHandleBatchUsesProcessors()
{
$testHandlers = array(new TestHandler(), new TestHandler());
$handler = new GroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true;
return $record;
});
$handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertTrue(count($test->getRecords()) === 2);
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
$this->assertTrue($records[1]['extra']['foo']);
}
}
}

View File

@@ -11,6 +11,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
use Monolog\TestCase;
use Monolog\Logger;
@@ -104,6 +105,13 @@ class NewRelicHandlerTest extends TestCase
$this->assertEquals($expected, self::$customParameters);
}
public function testThehandlerCanHandleTheRecordsFormattedUsingTheLineFormatter()
{
$handler = new StubNewRelicHandler();
$handler->setFormatter(new LineFormatter());
$handler->handle($this->getRecord(Logger::ERROR));
}
public function testTheAppNameIsNullByDefault()
{
$handler = new StubNewRelicHandler();

View File

@@ -12,19 +12,52 @@
namespace Monolog\Handler;
use Monolog\TestCase;
use PHPUnit_Framework_Error_Deprecated;
/**
* @covers Monolog\Handler\RotatingFileHandler
*/
class RotatingFileHandlerTest extends TestCase
{
/**
* This var should be private but then the anonymous function
* in the `setUp` method won't be able to set it. `$this` cant't
* be used in the anonymous function in `setUp` because PHP 5.3
* does not support it.
*/
public $lastError;
public function setUp()
{
$dir = __DIR__.'/Fixtures';
chmod($dir, 0777);
if (!is_writable($dir)) {
$this->markTestSkipped($dir.' must be writeable to test the RotatingFileHandler.');
$this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.');
}
$this->lastError = null;
$self = $this;
// workaround with &$self used for PHP 5.3
set_error_handler(function($code, $message) use (&$self) {
$self->lastError = array(
'code' => $code,
'message' => $message,
);
});
}
private function assertErrorWasTriggered($code, $message)
{
if (empty($this->lastError)) {
$this->fail(
sprintf(
'Failed asserting that error with code `%d` and message `%s` was triggered',
$code,
$message
)
);
}
$this->assertEquals($code, $this->lastError['code'], sprintf('Expected an error with code %d to be triggered, got `%s` instead', $code, $this->lastError['code']));
$this->assertEquals($message, $this->lastError['message'], sprintf('Expected an error with message `%d` to be triggered, got `%s` instead', $message, $this->lastError['message']));
}
public function testRotationCreatesNewFile()
@@ -43,14 +76,14 @@ class RotatingFileHandlerTest extends TestCase
/**
* @dataProvider rotationTests
*/
public function testRotation($createFile)
public function testRotation($createFile, $dateFormat, $timeCallback)
{
touch($old1 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot');
touch($old2 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 2).'.rot');
touch($old3 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 3).'.rot');
touch($old4 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 4).'.rot');
touch($old1 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-1)).'.rot');
touch($old2 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-2)).'.rot');
touch($old3 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-3)).'.rot');
touch($old4 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-4)).'.rot');
$log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
$log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot';
if ($createFile) {
touch($log);
@@ -58,6 +91,7 @@ class RotatingFileHandlerTest extends TestCase
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFormatter($this->getIdentityFormatter());
$handler->setFilenameFormat('{filename}-{date}', $dateFormat);
$handler->handle($this->getRecord());
$handler->close();
@@ -72,11 +106,88 @@ class RotatingFileHandlerTest extends TestCase
public function rotationTests()
{
$now = time();
$dayCallback = function($ago) use ($now) {
return $now + 86400 * $ago;
};
$monthCallback = function($ago) {
return gmmktime(0, 0, 0, date('n') + $ago, date('d'), date('Y'));
};
$yearCallback = function($ago) {
return gmmktime(0, 0, 0, date('n'), date('d'), date('Y') + $ago);
};
return array(
'Rotation is triggered when the file of the current day is not present'
=> array(true),
'Rotation is not triggered when the file is already present'
=> array(false),
=> array(true, RotatingFileHandler::FILE_PER_DAY, $dayCallback),
'Rotation is not triggered when the file of the current day is already present'
=> array(false, RotatingFileHandler::FILE_PER_DAY, $dayCallback),
'Rotation is triggered when the file of the current month is not present'
=> array(true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback),
'Rotation is not triggered when the file of the current month is already present'
=> array(false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback),
'Rotation is triggered when the file of the current year is not present'
=> array(true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback),
'Rotation is not triggered when the file of the current year is already present'
=> array(false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback),
);
}
/**
* @dataProvider dateFormatProvider
*/
public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFilenameFormat('{filename}-{date}', $dateFormat);
if (!$valid) {
$this->assertErrorWasTriggered(
E_USER_DEPRECATED,
'Invalid date format - format must be one of RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), '.
'RotatingFileHandler::FILE_PER_MONTH ("Y-m") or RotatingFileHandler::FILE_PER_YEAR ("Y"), '.
'or you can set one of the date formats using slashes, underscores and/or dots instead of dashes.'
);
}
}
public function dateFormatProvider()
{
return array(
array(RotatingFileHandler::FILE_PER_DAY, true),
array(RotatingFileHandler::FILE_PER_MONTH, true),
array(RotatingFileHandler::FILE_PER_YEAR, true),
array('m-d-Y', false),
array('Y-m-d-h-i', false)
);
}
/**
* @dataProvider filenameFormatProvider
*/
public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY);
if (!$valid) {
$this->assertErrorWasTriggered(
E_USER_DEPRECATED,
'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.'
);
}
}
public function filenameFormatProvider()
{
return array(
array('{filename}', false),
array('{filename}-{date}', true),
array('{date}', true),
array('foobar-{date}', true),
array('foo-{date}-bar', true),
array('{date}-foobar', true),
array('foobar', false),
);
}
@@ -95,5 +206,6 @@ class RotatingFileHandlerTest extends TestCase
foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
unlink($file);
}
restore_error_handler();
}
}

View File

@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
/**
* @author Greg Kedzierski <greg@gregkedzierski.com>
@@ -57,6 +58,23 @@ class SlackHandlerTest extends TestCase
$this->assertRegexp('/token=myToken&channel=channel1&username=Monolog&text=&attachments=.*$/', $content);
}
public function testWriteContentUsesFormatterIfProvided()
{
$this->createHandler('myToken', 'channel1', 'Monolog', false);
$this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->createHandler('myToken', 'channel1', 'Monolog', false);
$this->handler->setFormatter(new LineFormatter('foo--%message%'));
$this->handler->handle($this->getRecord(Logger::CRITICAL, 'test2'));
fseek($this->res, 0);
$content2 = fread($this->res, 1024);
$this->assertRegexp('/token=myToken&channel=channel1&username=Monolog&text=test1.*$/', $content);
$this->assertRegexp('/token=myToken&channel=channel1&username=Monolog&text=foo--test2.*$/', $content2);
}
public function testWriteContentWithEmoji()
{
$this->createHandler('myToken', 'channel1', 'Monolog', true, 'alien');