1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-04 20:27:31 +02:00

Merge branch '1.x'

This commit is contained in:
Jordi Boggiano
2016-12-16 08:47:02 +01:00
7 changed files with 201 additions and 104 deletions

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler\Slack; namespace Monolog\Handler\Slack;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
/** /**
@@ -41,15 +41,15 @@ class SlackRecord
/** /**
* Name of a bot * Name of a bot
* @var string * @var string|null
*/ */
private $username; private $username;
/** /**
* Emoji icon name * User icon e.g. 'ghost', 'http://example.com/user.png'
* @var string * @var string
*/ */
private $iconEmoji; private $userIcon;
/** /**
* Whether the message should be added to Slack as attachment (plain text otherwise) * Whether the message should be added to Slack as attachment (plain text otherwise)
@@ -69,43 +69,52 @@ class SlackRecord
*/ */
private $includeContextAndExtra; private $includeContextAndExtra;
/**
* Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
* @var array
*/
private $excludeFields;
/** /**
* @var FormatterInterface * @var FormatterInterface
*/ */
private $formatter; private $formatter;
/** /**
* @var LineFormatter * @var NormalizerFormatter
*/ */
private $lineFormatter; private $normalizerFormatter;
public function __construct($channel = null, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, FormatterInterface $formatter = null) public function __construct($channel = null, $username = null, $useAttachment = true, $userIcon = null, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array(), FormatterInterface $formatter = null)
{ {
$this->channel = $channel; $this->channel = $channel;
$this->username = $username; $this->username = $username;
$this->iconEmoji = trim($iconEmoji, ':'); $this->userIcon = trim($userIcon, ':');
$this->useAttachment = $useAttachment; $this->useAttachment = $useAttachment;
$this->useShortAttachment = $useShortAttachment; $this->useShortAttachment = $useShortAttachment;
$this->includeContextAndExtra = $includeContextAndExtra; $this->includeContextAndExtra = $includeContextAndExtra;
$this->excludeFields = $excludeFields;
$this->formatter = $formatter; $this->formatter = $formatter;
if ($this->includeContextAndExtra) { if ($this->includeContextAndExtra) {
$this->lineFormatter = new LineFormatter(); $this->normalizerFormatter = new NormalizerFormatter();
} }
} }
public function getSlackData(array $record) public function getSlackData(array $record)
{ {
$dataArray = array( $dataArray = array();
'username' => $this->username, $record = $this->excludeFields($record);
'text' => '',
); if ($this->username) {
$dataArray['username'] = $this->username;
}
if ($this->channel) { if ($this->channel) {
$dataArray['channel'] = $this->channel; $dataArray['channel'] = $this->channel;
} }
if ($this->formatter) { if ($this->formatter && !$this->useAttachment) {
$message = $this->formatter->format($record); $message = $this->formatter->format($record);
} else { } else {
$message = $record['message']; $message = $record['message'];
@@ -117,15 +126,18 @@ class SlackRecord
'text' => $message, 'text' => $message,
'color' => $this->getAttachmentColor($record['level']), 'color' => $this->getAttachmentColor($record['level']),
'fields' => array(), 'fields' => array(),
'mrkdwn_in' => array('fields'),
'ts' => $record['datetime']->getTimestamp()
); );
if ($this->useShortAttachment) { if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name']; $attachment['title'] = $record['level_name'];
} else { } else {
$attachment['title'] = 'Message'; $attachment['title'] = 'Message';
$attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name'], true); $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']);
} }
if ($this->includeContextAndExtra) { if ($this->includeContextAndExtra) {
foreach (array('extra', 'context') as $key) { foreach (array('extra', 'context') as $key) {
if (empty($record[$key])) { if (empty($record[$key])) {
@@ -135,8 +147,7 @@ class SlackRecord
if ($this->useShortAttachment) { if ($this->useShortAttachment) {
$attachment['fields'][] = $this->generateAttachmentField( $attachment['fields'][] = $this->generateAttachmentField(
ucfirst($key), ucfirst($key),
$this->stringify($record[$key]), $record[$key]
true
); );
} else { } else {
// Add all extra fields as individual fields in attachment // Add all extra fields as individual fields in attachment
@@ -153,8 +164,12 @@ class SlackRecord
$dataArray['text'] = $message; $dataArray['text'] = $message;
} }
if ($this->iconEmoji) { if ($this->userIcon) {
$dataArray['icon_emoji'] = ":{$this->iconEmoji}:"; if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) {
$dataArray['icon_url'] = $this->userIcon;
} else {
$dataArray['icon_emoji'] = ":{$this->userIcon}:";
}
} }
return $dataArray; return $dataArray;
@@ -185,22 +200,20 @@ class SlackRecord
* Stringifies an array of key/value pairs to be used in attachment fields * Stringifies an array of key/value pairs to be used in attachment fields
* *
* @param array $fields * @param array $fields
* @return string|null *
* @return string
*/ */
public function stringify($fields) public function stringify($fields)
{ {
if (!$this->lineFormatter) { $normalized = $this->normalizerFormatter->format($fields);
return null; $prettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128;
}
$string = ''; $hasSecondDimension = count(array_filter($normalized, 'is_array'));
foreach ($fields as $var => $val) { $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric'));
$string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
}
$string = rtrim($string, " |"); return $hasSecondDimension || $hasNonNumericKeys
? json_encode($normalized, $prettyPrintFlag)
return $string; : json_encode($normalized);
} }
/** /**
@@ -217,16 +230,20 @@ class SlackRecord
* Generates attachment field * Generates attachment field
* *
* @param string $title * @param string $title
* @param string|array $value * @param string|array $value\
* @param bool $short *
* @return array * @return array
*/ */
private function generateAttachmentField($title, $value, $short) private function generateAttachmentField($title, $value)
{ {
$value = is_array($value)
? sprintf('```%s```', $this->stringify($value))
: $value;
return array( return array(
'title' => $title, 'title' => $title,
'value' => is_array($value) ? $this->lineFormatter->stringify($value) : $value, 'value' => $value,
'short' => $short 'short' => false
); );
} }
@@ -234,15 +251,44 @@ class SlackRecord
* Generates a collection of attachment fields from array * Generates a collection of attachment fields from array
* *
* @param array $data * @param array $data
*
* @return array * @return array
*/ */
private function generateAttachmentFields(array $data) private function generateAttachmentFields(array $data)
{ {
$fields = array(); $fields = array();
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$fields[] = $this->generateAttachmentField($key, $value, false); $fields[] = $this->generateAttachmentField($key, $value);
} }
return $fields; return $fields;
} }
/**
* Get a copy of record with fields excluded according to $this->excludeFields
*
* @param array $record
*
* @return array
*/
private function excludeFields(array $record)
{
foreach ($this->excludeFields as $field) {
$keys = explode('.', $field);
$node = &$record;
$lastKey = end($keys);
foreach ($keys as $key) {
if (!isset($node[$key])) {
break;
}
if ($lastKey === $key) {
unset($node[$key]);
break;
}
$node = &$node[$key];
}
}
return $record;
}
} }

View File

@@ -38,16 +38,17 @@ class SlackHandler extends SocketHandler
/** /**
* @param string $token Slack API token * @param string $token Slack API token
* @param string $channel Slack channel (encoded ID or name) * @param string $channel Slack channel (encoded ID or name)
* @param string $username Name of a bot * @param string|null $username Name of a bot
* @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
* @param string|null $iconEmoji The emoji name to use (or null) * @param string|null $iconEmoji The emoji name to use (or null)
* @param int $level The minimum logging level at which this handler will be triggered * @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
* @param bool $includeContextAndExtra Whether the attachment should include context and extra data * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
* @throws MissingExtensionException If no OpenSSL PHP extension configured * @throws MissingExtensionException If no OpenSSL PHP extension configured
*/ */
public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false) public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array())
{ {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
@@ -62,6 +63,7 @@ class SlackHandler extends SocketHandler
$iconEmoji, $iconEmoji,
$useShortAttachment, $useShortAttachment,
$includeContextAndExtra, $includeContextAndExtra,
$excludeFields,
$this->formatter $this->formatter
); );

View File

@@ -38,15 +38,16 @@ class SlackWebhookHandler extends AbstractProcessingHandler
/** /**
* @param string $webhookUrl Slack Webhook URL * @param string $webhookUrl Slack Webhook URL
* @param string|null $channel Slack channel (encoded ID or name) * @param string|null $channel Slack channel (encoded ID or name)
* @param string $username Name of a bot * @param string|null $username Name of a bot
* @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
* @param string|null $iconEmoji The emoji name to use (or null) * @param string|null $iconEmoji The emoji name to use (or null)
* @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
* @param bool $includeContextAndExtra Whether the attachment should include context and extra data * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
* @param int $level The minimum logging level at which this handler will be triggered * @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
*/ */
public function __construct($webhookUrl, $channel = null, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true) public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true, array $excludeFields = array())
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -59,6 +60,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
$iconEmoji, $iconEmoji,
$useShortAttachment, $useShortAttachment,
$includeContextAndExtra, $includeContextAndExtra,
$excludeFields,
$this->formatter $this->formatter
); );
} }

View File

@@ -19,11 +19,11 @@ use Monolog\Test\TestCase;
*/ */
class SlackRecordTest extends TestCase class SlackRecordTest extends TestCase
{ {
private $channel; private $jsonPrettyPrintFlag;
protected function setUp() protected function setUp()
{ {
$this->channel = 'monolog_alerts'; $this->jsonPrettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128;
} }
public function dataGetAttachmentColor() public function dataGetAttachmentColor()
@@ -39,6 +39,7 @@ class SlackRecordTest extends TestCase
array(Logger::EMERGENCY, SlackRecord::COLOR_DANGER), array(Logger::EMERGENCY, SlackRecord::COLOR_DANGER),
); );
} }
/** /**
* @dataProvider dataGetAttachmentColor * @dataProvider dataGetAttachmentColor
* @param int $logLevel * @param int $logLevel
@@ -47,7 +48,7 @@ class SlackRecordTest extends TestCase
*/ */
public function testGetAttachmentColor($logLevel, $expectedColour) public function testGetAttachmentColor($logLevel, $expectedColour)
{ {
$slackRecord = new SlackRecord('#test'); $slackRecord = new SlackRecord();
$this->assertSame( $this->assertSame(
$expectedColour, $expectedColour,
$slackRecord->getAttachmentColor($logLevel) $slackRecord->getAttachmentColor($logLevel)
@@ -56,26 +57,20 @@ class SlackRecordTest extends TestCase
public function testAddsChannel() public function testAddsChannel()
{ {
$record = new SlackRecord($this->channel); $channel = '#test';
$record = new SlackRecord($channel);
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('channel', $data); $this->assertArrayHasKey('channel', $data);
$this->assertSame($this->channel, $data['channel']); $this->assertSame($channel, $data['channel']);
} }
public function testStringifyReturnsNullWithNoLineFormatter() public function testNoUsernameByDefault()
{ {
$slackRecord = new SlackRecord('#test'); $record = new SlackRecord();
$this->assertNull($slackRecord->stringify(array('foo' => 'bar')));
}
public function testAddsDefaultUsername()
{
$record = new SlackRecord($this->channel);
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('username', $data); $this->assertArrayNotHasKey('username', $data);
$this->assertSame('Monolog', $data['username']);
} }
/** /**
@@ -83,17 +78,24 @@ class SlackRecordTest extends TestCase
*/ */
public function dataStringify() public function dataStringify()
{ {
$jsonPrettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128;
$multipleDimensions = array(array(1, 2));
$numericKeys = array('library' => 'monolog');
$singleDimension = array(1, 'Hello', 'Jordi');
return array( return array(
array(array(), ''), array(array(), '[]'),
array(array('foo' => 'bar'), 'foo: bar'), array($multipleDimensions, json_encode($multipleDimensions, $jsonPrettyPrintFlag)),
array(array('Foo' => 'bAr'), 'Foo: bAr'), array($numericKeys, json_encode($numericKeys, $jsonPrettyPrintFlag)),
array($singleDimension, json_encode($singleDimension))
); );
} }
/** /**
* @dataProvider dataStringify * @dataProvider dataStringify
*/ */
public function testStringifyWithLineFormatter($fields, $expectedResult) public function testStringify($fields, $expectedResult)
{ {
$slackRecord = new SlackRecord( $slackRecord = new SlackRecord(
'#test', '#test',
@@ -110,7 +112,7 @@ class SlackRecordTest extends TestCase
public function testAddsCustomUsername() public function testAddsCustomUsername()
{ {
$username = 'Monolog bot'; $username = 'Monolog bot';
$record = new SlackRecord($this->channel, $username); $record = new SlackRecord(null, $username);
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('username', $data); $this->assertArrayHasKey('username', $data);
@@ -119,7 +121,7 @@ class SlackRecordTest extends TestCase
public function testNoIcon() public function testNoIcon()
{ {
$record = new SlackRecord($this->channel); $record = new SlackRecord();
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayNotHasKey('icon_emoji', $data); $this->assertArrayNotHasKey('icon_emoji', $data);
@@ -127,25 +129,22 @@ class SlackRecordTest extends TestCase
public function testAddsIcon() public function testAddsIcon()
{ {
$record = new SlackRecord($this->channel, 'Monolog', true, 'ghost'); $record = $this->getRecord();
$data = $record->getSlackData($this->getRecord()); $slackRecord = new SlackRecord(null, null, false, 'ghost');
$data = $slackRecord->getSlackData($record);
$slackRecord2 = new SlackRecord(null, null, false, 'http://github.com/Seldaek/monolog');
$data2 = $slackRecord2->getSlackData($record);
$this->assertArrayHasKey('icon_emoji', $data); $this->assertArrayHasKey('icon_emoji', $data);
$this->assertSame(':ghost:', $data['icon_emoji']); $this->assertSame(':ghost:', $data['icon_emoji']);
} $this->assertArrayHasKey('icon_url', $data2);
$this->assertSame('http://github.com/Seldaek/monolog', $data2['icon_url']);
public function testAddsEmptyTextIfUseAttachment()
{
$record = new SlackRecord($this->channel);
$data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('text', $data);
$this->assertSame('', $data['text']);
} }
public function testAttachmentsNotPresentIfNoAttachment() public function testAttachmentsNotPresentIfNoAttachment()
{ {
$record = new SlackRecord($this->channel, 'Monolog', false); $record = new SlackRecord(null, null, false);
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayNotHasKey('attachments', $data); $this->assertArrayNotHasKey('attachments', $data);
@@ -153,7 +152,7 @@ class SlackRecordTest extends TestCase
public function testAddsOneAttachment() public function testAddsOneAttachment()
{ {
$record = new SlackRecord($this->channel); $record = new SlackRecord();
$data = $record->getSlackData($this->getRecord()); $data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('attachments', $data); $this->assertArrayHasKey('attachments', $data);
@@ -161,10 +160,10 @@ class SlackRecordTest extends TestCase
$this->assertInternalType('array', $data['attachments'][0]); $this->assertInternalType('array', $data['attachments'][0]);
} }
public function testTextEqualsMessageIfNoFormatter() public function testTextEqualsMessageIfNoAttachment()
{ {
$message = 'Test message'; $message = 'Test message';
$record = new SlackRecord($this->channel, 'Monolog', false); $record = new SlackRecord(null, null, false);
$data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message));
$this->assertArrayHasKey('text', $data); $this->assertArrayHasKey('text', $data);
@@ -186,7 +185,7 @@ class SlackRecordTest extends TestCase
->will($this->returnCallback(function ($record) { return $record['message'] . 'test1'; })); ->will($this->returnCallback(function ($record) { return $record['message'] . 'test1'; }));
$message = 'Test message'; $message = 'Test message';
$record = new SlackRecord($this->channel, 'Monolog', false, null, false, false, $formatter); $record = new SlackRecord(null, null, false, null, false, false, array(), $formatter);
$data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message));
$this->assertArrayHasKey('text', $data); $this->assertArrayHasKey('text', $data);
@@ -202,7 +201,7 @@ class SlackRecordTest extends TestCase
public function testAddsFallbackAndTextToAttachment() public function testAddsFallbackAndTextToAttachment()
{ {
$message = 'Test message'; $message = 'Test message';
$record = new SlackRecord($this->channel); $record = new SlackRecord(null);
$data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message));
$this->assertSame($message, $data['attachments'][0]['text']); $this->assertSame($message, $data['attachments'][0]['text']);
@@ -211,7 +210,7 @@ class SlackRecordTest extends TestCase
public function testMapsLevelToColorAttachmentColor() public function testMapsLevelToColorAttachmentColor()
{ {
$record = new SlackRecord($this->channel); $record = new SlackRecord(null);
$errorLoggerRecord = $this->getRecord(Logger::ERROR); $errorLoggerRecord = $this->getRecord(Logger::ERROR);
$emergencyLoggerRecord = $this->getRecord(Logger::EMERGENCY); $emergencyLoggerRecord = $this->getRecord(Logger::EMERGENCY);
$warningLoggerRecord = $this->getRecord(Logger::WARNING); $warningLoggerRecord = $this->getRecord(Logger::WARNING);
@@ -238,7 +237,7 @@ class SlackRecordTest extends TestCase
{ {
$level = Logger::ERROR; $level = Logger::ERROR;
$levelName = Logger::getLevelName($level); $levelName = Logger::getLevelName($level);
$record = new SlackRecord($this->channel, 'Monolog', true, null, true); $record = new SlackRecord(null, null, true, null, true);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$attachment = $data['attachments'][0]; $attachment = $data['attachments'][0];
@@ -252,9 +251,11 @@ class SlackRecordTest extends TestCase
{ {
$level = Logger::ERROR; $level = Logger::ERROR;
$levelName = Logger::getLevelName($level); $levelName = Logger::getLevelName($level);
$record = new SlackRecord($this->channel, 'Monolog', true, null, true, true); $context = array('test' => 1);
$loggerRecord = $this->getRecord($level, 'test', array('test' => 1)); $extra = array('tags' => array('web'));
$loggerRecord['extra'] = array('tags' => array('web')); $record = new SlackRecord(null, null, true, null, true, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord); $data = $record->getSlackData($loggerRecord);
$attachment = $data['attachments'][0]; $attachment = $data['attachments'][0];
@@ -266,13 +267,13 @@ class SlackRecordTest extends TestCase
array( array(
array( array(
'title' => 'Extra', 'title' => 'Extra',
'value' => 'tags: ["web"]', 'value' => sprintf('```%s```', json_encode($extra, $this->jsonPrettyPrintFlag)),
'short' => true 'short' => false
), ),
array( array(
'title' => 'Context', 'title' => 'Context',
'value' => 'test: 1', 'value' => sprintf('```%s```', json_encode($context, $this->jsonPrettyPrintFlag)),
'short' => true 'short' => false
) )
), ),
$attachment['fields'] $attachment['fields']
@@ -283,7 +284,7 @@ class SlackRecordTest extends TestCase
{ {
$level = Logger::ERROR; $level = Logger::ERROR;
$levelName = Logger::getLevelName($level); $levelName = Logger::getLevelName($level);
$record = new SlackRecord($this->channel, 'Monolog', true, null); $record = new SlackRecord(null, null, true, null);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$attachment = $data['attachments'][0]; $attachment = $data['attachments'][0];
@@ -295,7 +296,7 @@ class SlackRecordTest extends TestCase
array(array( array(array(
'title' => 'Level', 'title' => 'Level',
'value' => $levelName, 'value' => $levelName,
'short' => true 'short' => false
)), )),
$attachment['fields'] $attachment['fields']
); );
@@ -305,25 +306,27 @@ class SlackRecordTest extends TestCase
{ {
$level = Logger::ERROR; $level = Logger::ERROR;
$levelName = Logger::getLevelName($level); $levelName = Logger::getLevelName($level);
$record = new SlackRecord($this->channel, 'Monolog', true, null, false, true); $context = array('test' => 1);
$loggerRecord = $this->getRecord($level, 'test', array('test' => 1)); $extra = array('tags' => array('web'));
$loggerRecord['extra'] = array('tags' => array('web')); $record = new SlackRecord(null, null, true, null, false, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord); $data = $record->getSlackData($loggerRecord);
$expectedFields = array( $expectedFields = array(
array( array(
'title' => 'Level', 'title' => 'Level',
'value' => $levelName, 'value' => $levelName,
'short' => true, 'short' => false,
), ),
array( array(
'title' => 'tags', 'title' => 'tags',
'value' => '["web"]', 'value' => sprintf('```%s```', json_encode($extra['tags'])),
'short' => false 'short' => false
), ),
array( array(
'title' => 'test', 'title' => 'test',
'value' => 1, 'value' => $context['test'],
'short' => false 'short' => false
) )
); );
@@ -338,4 +341,47 @@ class SlackRecordTest extends TestCase
$attachment['fields'] $attachment['fields']
); );
} }
public function testAddsTimestampToAttachment()
{
$record = $this->getRecord();
$slackRecord = new SlackRecord();
$data = $slackRecord->getSlackData($this->getRecord());
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('ts', $attachment);
$this->assertSame($record['datetime']->getTimestamp(), $attachment['ts']);
}
public function testExcludeExtraAndContextFields()
{
$record = $this->getRecord(
Logger::WARNING,
'test',
array('info' => array('library' => 'monolog', 'author' => 'Jordi'))
);
$record['extra'] = array('tags' => array('web', 'cli'));
$slackRecord = new SlackRecord(null, null, true, null, false, true, array('context.info.library', 'extra.tags.1'));
$data = $slackRecord->getSlackData($record);
$attachment = $data['attachments'][0];
$expected = array(
array(
'title' => 'info',
'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), $this->jsonPrettyPrintFlag)),
'short' => false
),
array(
'title' => 'tags',
'value' => sprintf('```%s```', json_encode(array('web'))),
'short' => false
),
);
foreach ($expected as $field) {
$this->assertNotFalse(array_search($field, $attachment['fields']));
break;
}
}
} }

View File

@@ -32,11 +32,10 @@ class SlackWebhookHandlerTest extends TestCase
public function testConstructorMinimal() public function testConstructorMinimal()
{ {
$handler = new SlackWebhookHandler(self::WEBHOOK_URL); $handler = new SlackWebhookHandler(self::WEBHOOK_URL);
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord(); $slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord); $this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array( $this->assertEquals(array(
'username' => 'Monolog',
'text' => '',
'attachments' => array( 'attachments' => array(
array( array(
'fallback' => 'test', 'fallback' => 'test',
@@ -46,13 +45,15 @@ class SlackWebhookHandlerTest extends TestCase
array( array(
'title' => 'Level', 'title' => 'Level',
'value' => 'WARNING', 'value' => 'WARNING',
'short' => true, 'short' => false,
), ),
), ),
'title' => 'Message', 'title' => 'Message',
'mrkdwn_in' => array('fields'),
'ts' => $record['datetime']->getTimestamp(),
), ),
), ),
), $slackRecord->getSlackData($this->getRecord())); ), $slackRecord->getSlackData($record));
} }
/** /**