summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorAnton Nizhegorodov <hookman.ru@gmail.com>2016-12-13 16:25:55 +0200
committerJordi Boggiano <j.boggiano@seld.be>2016-12-13 15:25:55 +0100
commitb732364e70a615231f15944e015b31d0d77bf9f5 (patch)
treedc506ea54d7f0ce47b92171f8ef36a651ad87e66 /src
parentfdd6780ffd2f1aa1d7af7d6c69f186bf17d35cd4 (diff)
downloadmonolog-b732364e70a615231f15944e015b31d0d77bf9f5.zip
monolog-b732364e70a615231f15944e015b31d0d77bf9f5.tar.gz
monolog-b732364e70a615231f15944e015b31d0d77bf9f5.tar.bz2
Slack improvements (#894)
- [x] Exclude `extra`/`context`, `datetime`, `level` from message when attachment is used - [x] Use `ts` attachment key to display `datetime` considering user timezone - [x] [Support](https://github.com/Seldaek/monolog/pull/846#issuecomment-249528719) custom user images - [x] [Allow](https://github.com/Seldaek/monolog/pull/894#issuecomment-263532399) to setup username from slack - [x] [Improve](https://github.com/Seldaek/monolog/pull/846#issuecomment-261529198) array formatting within `context`/`extra` - [x] [Support](https://github.com/Seldaek/monolog/issues/745) `include_stacktraces` option when attachment is not used and always include stacktraces when attachment is used - [x] Support `extra`/`context` field exclusion - [x] Update tests
Diffstat (limited to 'src')
-rw-r--r--src/Monolog/Handler/Slack/SlackRecord.php128
-rw-r--r--src/Monolog/Handler/SlackHandler.php6
-rw-r--r--src/Monolog/Handler/SlackWebhookHandler.php6
3 files changed, 95 insertions, 45 deletions
diff --git a/src/Monolog/Handler/Slack/SlackRecord.php b/src/Monolog/Handler/Slack/SlackRecord.php
index cb0b871..38bc838 100644
--- a/src/Monolog/Handler/Slack/SlackRecord.php
+++ b/src/Monolog/Handler/Slack/SlackRecord.php
@@ -12,7 +12,7 @@
namespace Monolog\Handler\Slack;
use Monolog\Logger;
-use Monolog\Formatter\LineFormatter;
+use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface;
/**
@@ -41,15 +41,15 @@ class SlackRecord
/**
* Name of a bot
- * @var string
+ * @var string|null
*/
private $username;
/**
- * Emoji icon name
+ * User icon e.g. 'ghost', 'http://example.com/user.png'
* @var string
*/
- private $iconEmoji;
+ private $userIcon;
/**
* Whether the message should be added to Slack as attachment (plain text otherwise)
@@ -70,42 +70,51 @@ class SlackRecord
private $includeContextAndExtra;
/**
+ * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
+ * @var array
+ */
+ private $excludeFields;
+
+ /**
* @var FormatterInterface
*/
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->username = $username;
- $this->iconEmoji = trim($iconEmoji, ':');
+ $this->userIcon = trim($userIcon, ':');
$this->useAttachment = $useAttachment;
$this->useShortAttachment = $useShortAttachment;
$this->includeContextAndExtra = $includeContextAndExtra;
+ $this->excludeFields = $excludeFields;
$this->formatter = $formatter;
if ($this->includeContextAndExtra) {
- $this->lineFormatter = new LineFormatter();
+ $this->normalizerFormatter = new NormalizerFormatter();
}
}
public function getSlackData(array $record)
{
- $dataArray = array(
- 'username' => $this->username,
- 'text' => '',
- );
+ $dataArray = array();
+ $record = $this->excludeFields($record);
+
+ if ($this->username) {
+ $dataArray['username'] = $this->username;
+ }
if ($this->channel) {
$dataArray['channel'] = $this->channel;
}
- if ($this->formatter) {
+ if ($this->formatter && !$this->useAttachment) {
$message = $this->formatter->format($record);
} else {
$message = $record['message'];
@@ -113,19 +122,22 @@ class SlackRecord
if ($this->useAttachment) {
$attachment = array(
- 'fallback' => $message,
- 'text' => $message,
- 'color' => $this->getAttachmentColor($record['level']),
- 'fields' => array(),
+ 'fallback' => $message,
+ 'text' => $message,
+ 'color' => $this->getAttachmentColor($record['level']),
+ 'fields' => array(),
+ 'mrkdwn_in' => array('fields'),
+ 'ts' => $record['datetime']->getTimestamp()
);
if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name'];
} else {
$attachment['title'] = 'Message';
- $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name'], true);
+ $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']);
}
+
if ($this->includeContextAndExtra) {
foreach (array('extra', 'context') as $key) {
if (empty($record[$key])) {
@@ -135,8 +147,7 @@ class SlackRecord
if ($this->useShortAttachment) {
$attachment['fields'][] = $this->generateAttachmentField(
ucfirst($key),
- $this->stringify($record[$key]),
- true
+ $record[$key]
);
} else {
// Add all extra fields as individual fields in attachment
@@ -153,8 +164,12 @@ class SlackRecord
$dataArray['text'] = $message;
}
- if ($this->iconEmoji) {
- $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
+ if ($this->userIcon) {
+ if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) {
+ $dataArray['icon_url'] = $this->userIcon;
+ } else {
+ $dataArray['icon_emoji'] = ":{$this->userIcon}:";
+ }
}
return $dataArray;
@@ -184,23 +199,21 @@ class SlackRecord
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
- * @param array $fields
- * @return string|null
+ * @param array $fields
+ *
+ * @return string
*/
public function stringify($fields)
{
- if (!$this->lineFormatter) {
- return null;
- }
-
- $string = '';
- foreach ($fields as $var => $val) {
- $string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
- }
+ $normalized = $this->normalizerFormatter->format($fields);
+ $prettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128;
- $string = rtrim($string, " |");
+ $hasSecondDimension = count(array_filter($normalized, 'is_array'));
+ $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric'));
- return $string;
+ return $hasSecondDimension || $hasNonNumericKeys
+ ? json_encode($normalized, $prettyPrintFlag)
+ : json_encode($normalized);
}
/**
@@ -217,16 +230,20 @@ class SlackRecord
* Generates attachment field
*
* @param string $title
- * @param string|array $value
- * @param bool $short
+ * @param string|array $value\
+ *
* @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(
'title' => $title,
- 'value' => is_array($value) ? $this->lineFormatter->stringify($value) : $value,
- 'short' => $short
+ 'value' => $value,
+ 'short' => false
);
}
@@ -234,15 +251,44 @@ class SlackRecord
* Generates a collection of attachment fields from array
*
* @param array $data
+ *
* @return array
*/
private function generateAttachmentFields(array $data)
{
$fields = array();
foreach ($data as $key => $value) {
- $fields[] = $this->generateAttachmentField($key, $value, false);
+ $fields[] = $this->generateAttachmentField($key, $value);
}
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;
+ }
}
diff --git a/src/Monolog/Handler/SlackHandler.php b/src/Monolog/Handler/SlackHandler.php
index c2cca0c..9324fc9 100644
--- a/src/Monolog/Handler/SlackHandler.php
+++ b/src/Monolog/Handler/SlackHandler.php
@@ -38,16 +38,17 @@ class SlackHandler extends SocketHandler
/**
* @param string $token Slack API token
* @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 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 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 $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
*/
- 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')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
@@ -62,6 +63,7 @@ class SlackHandler extends SocketHandler
$iconEmoji,
$useShortAttachment,
$includeContextAndExtra,
+ $excludeFields,
$this->formatter
);
diff --git a/src/Monolog/Handler/SlackWebhookHandler.php b/src/Monolog/Handler/SlackWebhookHandler.php
index a2df0f1..0d3e3ea 100644
--- a/src/Monolog/Handler/SlackWebhookHandler.php
+++ b/src/Monolog/Handler/SlackWebhookHandler.php
@@ -38,15 +38,16 @@ class SlackWebhookHandler extends AbstractProcessingHandler
/**
* @param string $webhookUrl Slack Webhook URL
* @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 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 $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 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);
@@ -59,6 +60,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
$iconEmoji,
$useShortAttachment,
$includeContextAndExtra,
+ $excludeFields,
$this->formatter
);
}