1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-22 17:16:18 +02:00

Merge branch '1.x'

This commit is contained in:
Jordi Boggiano
2016-11-26 01:23:57 +01:00
11 changed files with 1010 additions and 171 deletions

View File

@@ -0,0 +1,248 @@
<?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\Handler\Slack;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface;
/**
* Slack record utility helping to log to Slack webhooks or API.
*
* @author Greg Kedzierski <greg@gregkedzierski.com>
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @see https://api.slack.com/incoming-webhooks
* @see https://api.slack.com/docs/message-attachments
*/
class SlackRecord
{
const COLOR_DANGER = 'danger';
const COLOR_WARNING = 'warning';
const COLOR_GOOD = 'good';
const COLOR_DEFAULT = '#e3e4e6';
/**
* Slack channel (encoded ID or name)
* @var string|null
*/
private $channel;
/**
* Name of a bot
* @var string
*/
private $username;
/**
* Emoji icon name
* @var string
*/
private $iconEmoji;
/**
* Whether the message should be added to Slack as attachment (plain text otherwise)
* @var bool
*/
private $useAttachment;
/**
* Whether the the context/extra messages added to Slack as attachments are in a short style
* @var bool
*/
private $useShortAttachment;
/**
* Whether the attachment should include context and extra data
* @var bool
*/
private $includeContextAndExtra;
/**
* @var FormatterInterface
*/
private $formatter;
/**
* @var LineFormatter
*/
private $lineFormatter;
public function __construct($channel = null, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, FormatterInterface $formatter = null)
{
$this->channel = $channel;
$this->username = $username;
$this->iconEmoji = trim($iconEmoji, ':');
$this->useAttachment = $useAttachment;
$this->useShortAttachment = $useShortAttachment;
$this->includeContextAndExtra = $includeContextAndExtra;
$this->formatter = $formatter;
if ($this->includeContextAndExtra) {
$this->lineFormatter = new LineFormatter();
}
}
public function getSlackData(array $record)
{
$dataArray = array(
'username' => $this->username,
'text' => '',
);
if ($this->channel) {
$dataArray['channel'] = $this->channel;
}
if ($this->formatter) {
$message = $this->formatter->format($record);
} else {
$message = $record['message'];
}
if ($this->useAttachment) {
$attachment = array(
'fallback' => $message,
'text' => $message,
'color' => $this->getAttachmentColor($record['level']),
'fields' => array(),
);
if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name'];
} else {
$attachment['title'] = 'Message';
$attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name'], true);
}
if ($this->includeContextAndExtra) {
foreach (array('extra', 'context') as $key) {
if (empty($record[$key])) {
continue;
}
if ($this->useShortAttachment) {
$attachment['fields'][] = $this->generateAttachmentField(
ucfirst($key),
$this->stringify($record[$key]),
true
);
} else {
// Add all extra fields as individual fields in attachment
$attachment['fields'] = array_merge(
$attachment['fields'],
$this->generateAttachmentFields($record[$key])
);
}
}
}
$dataArray['attachments'] = array($attachment);
} else {
$dataArray['text'] = $message;
}
if ($this->iconEmoji) {
$dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
}
return $dataArray;
}
/**
* Returned a Slack message attachment color associated with
* provided level.
*
* @param int $level
* @return string
*/
public function getAttachmentColor($level)
{
switch (true) {
case $level >= Logger::ERROR:
return self::COLOR_DANGER;
case $level >= Logger::WARNING:
return self::COLOR_WARNING;
case $level >= Logger::INFO:
return self::COLOR_GOOD;
default:
return self::COLOR_DEFAULT;
}
}
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
* @param array $fields
* @return string|null
*/
public function stringify($fields)
{
if (!$this->lineFormatter) {
return null;
}
$string = '';
foreach ($fields as $var => $val) {
$string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
}
$string = rtrim($string, " |");
return $string;
}
/**
* Sets the formatter
*
* @param FormatterInterface $formatter
*/
public function setFormatter(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
/**
* Generates attachment field
*
* @param string $title
* @param string|array $value
* @param bool $short
* @return array
*/
private function generateAttachmentField($title, $value, $short)
{
return array(
'title' => $title,
'value' => is_array($value) ? $this->lineFormatter->stringify($value) : $value,
'short' => $short
);
}
/**
* 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);
}
return $fields;
}
}

View File

@@ -11,8 +11,9 @@
namespace Monolog\Handler;
use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;
/**
* Sends notifications through Slack API
@@ -29,45 +30,10 @@ class SlackHandler extends SocketHandler
private $token;
/**
* Slack channel (encoded ID or name)
* @var string
* Instance of the SlackRecord util class preparing data for Slack API.
* @var SlackRecord
*/
private $channel;
/**
* Name of a bot
* @var string
*/
private $username;
/**
* Emoji icon name
* @var string
*/
private $iconEmoji;
/**
* Whether the message should be added to Slack as attachment (plain text otherwise)
* @var bool
*/
private $useAttachment;
/**
* Whether the the context/extra messages added to Slack as attachments are in a short style
* @var bool
*/
private $useShortAttachment;
/**
* Whether the attachment should include context and extra data
* @var bool
*/
private $includeContextAndExtra;
/**
* @var LineFormatter
*/
private $lineFormatter;
private $slackRecord;
/**
* @param string $token Slack API token
@@ -79,10 +45,9 @@ class SlackHandler extends SocketHandler
* @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 bool $printSimpleMessage Whether the attachment should include only the message without extradata
* @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, $printSimpleMessage = false)
public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false)
{
if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
@@ -90,17 +55,22 @@ class SlackHandler extends SocketHandler
parent::__construct('ssl://slack.com:443', $level, $bubble);
$this->token = $token;
$this->channel = $channel;
$this->username = $username;
$this->iconEmoji = is_string($iconEmoji) ? trim($iconEmoji, ':') : null;
$this->useAttachment = $useAttachment;
$this->useShortAttachment = $useShortAttachment;
$this->includeContextAndExtra = $includeContextAndExtra;
$this->slackRecord = new SlackRecord(
$channel,
$username,
$useAttachment,
$iconEmoji,
$useShortAttachment,
$includeContextAndExtra,
$this->formatter
);
if ($this->includeContextAndExtra && $this->useShortAttachment) {
$this->lineFormatter = new LineFormatter;
}
$this->token = $token;
}
public function getSlackRecord()
{
return $this->slackRecord;
}
/**
@@ -137,87 +107,11 @@ class SlackHandler extends SocketHandler
*/
protected function prepareContentData($record)
{
$dataArray = [
'token' => $this->token,
'channel' => $this->channel,
'username' => $this->username,
'text' => '',
'attachments' => [],
];
$dataArray = $this->slackRecord->getSlackData($record);
$dataArray['token'] = $this->token;
if ($this->formatter && !$printSimpleMessage) {
$message = $this->formatter->format($record);
} else {
$message = $record['message'];
}
if ($this->useAttachment) {
$attachment = [
'fallback' => $message,
'color' => $this->getAttachmentColor($record['level']),
'fields' => [],
];
if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name'];
$attachment['text'] = $message;
} else {
$attachment['title'] = 'Message';
$attachment['text'] = $message;
$attachment['fields'][] = [
'title' => 'Level',
'value' => $record['level_name'],
'short' => true,
];
}
if ($this->includeContextAndExtra) {
if (!empty($record['extra'])) {
if ($this->useShortAttachment) {
$attachment['fields'][] = [
'title' => "Extra",
'value' => $this->stringify($record['extra']),
'short' => $this->useShortAttachment,
];
} else {
// Add all extra fields as individual fields in attachment
foreach ($record['extra'] as $var => $val) {
$attachment['fields'][] = [
'title' => $var,
'value' => $val,
'short' => $this->useShortAttachment,
];
}
}
}
if (!empty($record['context'])) {
if ($this->useShortAttachment) {
$attachment['fields'][] = [
'title' => "Context",
'value' => $this->stringify($record['context']),
'short' => $this->useShortAttachment,
];
} else {
// Add all context fields as individual fields in attachment
foreach ($record['context'] as $var => $val) {
$attachment['fields'][] = [
'title' => $var,
'value' => $val,
'short' => $this->useShortAttachment,
];
}
}
}
}
$dataArray['attachments'] = json_encode([$attachment]);
} else {
$dataArray['text'] = $message;
}
if ($this->iconEmoji) {
$dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
if (!empty($dataArray['attachments'])) {
$dataArray['attachments'] = json_encode($dataArray['attachments']);
}
return $dataArray;
@@ -261,19 +155,16 @@ class SlackHandler extends SocketHandler
*
* @param int $level
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function getAttachmentColor($level)
{
switch (true) {
case $level >= Logger::ERROR:
return 'danger';
case $level >= Logger::WARNING:
return 'warning';
case $level >= Logger::INFO:
return 'good';
default:
return '#e3e4e6';
}
trigger_error(
'SlackHandler::getAttachmentColor() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
return $this->slackRecord->getAttachmentColor($level);
}
/**
@@ -281,16 +172,31 @@ class SlackHandler extends SocketHandler
*
* @param array $fields
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function stringify($fields)
{
$string = '';
foreach ($fields as $var => $val) {
$string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
}
trigger_error(
'SlackHandler::stringify() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
$string = rtrim($string, " |");
return $this->slackRecord->stringify($fields);
}
return $string;
public function setFormatter(FormatterInterface $formatter)
{
parent::setFormatter($formatter);
$this->slackRecord->setFormatter($formatter);
return $this;
}
public function getFormatter()
{
$formatter = parent::getFormatter();
$this->slackRecord->setFormatter($formatter);
return $formatter;
}
}

View File

@@ -0,0 +1,108 @@
<?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\Handler;
use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use Monolog\Handler\Slack\SlackRecord;
/**
* Sends notifications through Slack Webhooks
*
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @see https://api.slack.com/incoming-webhooks
*/
class SlackWebhookHandler extends AbstractProcessingHandler
{
/**
* Slack Webhook token
* @var string
*/
private $webhookUrl;
/**
* Instance of the SlackRecord util class preparing data for Slack API.
* @var SlackRecord
*/
private $slackRecord;
/**
* @param string $webhookUrl Slack Webhook URL
* @param string|null $channel Slack channel (encoded ID or name)
* @param string $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
*/
public function __construct($webhookUrl, $channel = null, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true)
{
parent::__construct($level, $bubble);
$this->webhookUrl = $webhookUrl;
$this->slackRecord = new SlackRecord(
$channel,
$username,
$useAttachment,
$iconEmoji,
$useShortAttachment,
$includeContextAndExtra,
$this->formatter
);
}
public function getSlackRecord()
{
return $this->slackRecord;
}
/**
* {@inheritdoc}
*
* @param array $record
*/
protected function write(array $record)
{
$postData = $this->slackRecord->getSlackData($record);
$postString = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->webhookUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $postString));
Curl\Util::execute($ch);
}
public function setFormatter(FormatterInterface $formatter)
{
parent::setFormatter($formatter);
$this->slackRecord->setFormatter($formatter);
return $this;
}
public function getFormatter()
{
$formatter = parent::getFormatter();
$this->slackRecord->setFormatter($formatter);
return $formatter;
}
}

View File

@@ -0,0 +1,80 @@
<?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\Handler;
use Monolog\Logger;
/**
* Sends notifications through Slack's Slackbot
*
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @see https://slack.com/apps/A0F81R8ET-slackbot
*/
class SlackbotHandler extends AbstractProcessingHandler
{
/**
* The slug of the Slack team
* @var string
*/
private $slackTeam;
/**
* Slackbot token
* @var string
*/
private $token;
/**
* Slack channel name
* @var string
*/
private $channel;
/**
* @param string $slackTeam Slack team slug
* @param string $token Slackbot token
* @param string $channel Slack channel (encoded ID or name)
* @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
*/
public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, $bubble = true)
{
parent::__construct($level, $bubble);
$this->slackTeam = $slackTeam;
$this->token = $token;
$this->channel = $channel;
}
/**
* {@inheritdoc}
*
* @param array $record
*/
protected function write(array $record)
{
$slackbotUrl = sprintf(
'https://%s.slack.com/services/hooks/slackbot?token=%s&channel=%s',
$this->slackTeam,
$this->token,
$this->channel
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $slackbotUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $record['message']);
Curl\Util::execute($ch);
}
}