Last active
July 17, 2016 15:24
-
-
Save egruz/8855636 to your computer and use it in GitHub Desktop.
Monolog Slack Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Monolog Slack Handler | |
* | |
* This adds the ability to post a message to your Chosen Slack channel easily with Monolog. | |
* | |
* Here is an example of using this handler: | |
* $logger->pushHandler(new SlackHandler("your-account-name", "your-token-code", "#your-channel-name", "name-to-post-message-as", "url-to-image-file", Logger::INFO, true)); | |
* | |
* https://slack.com/ | |
* | |
* (c) Graham Cassidy <[email protected]> | |
* | |
*/ | |
namespace Monolog\Handler; | |
/** | |
* Basic Handler to post to Slack | |
* | |
* @author Graham Cassidy | |
*/ | |
class SlackHandler extends MailHandler | |
{ | |
protected $token; | |
protected $channel; | |
protected $username; | |
protected $icon; | |
/** | |
* @param string $token Your Slack Token | |
* @param string $channel Slack channel to post in | |
* @param string $username Username you'd like to display message as | |
* @param string $icon URL to custom icon | |
*/ | |
public function __construct($account, $token, $channel, $username, $icon, $level = Logger::ERROR, $bubble = true) | |
{ | |
parent::__construct($level, $bubble); | |
$this->account = $account; | |
$this->token = $token; | |
$this->channel = $channel; | |
$this->username = $username; | |
$this->icon = $icon; | |
} | |
/** | |
* Post the message to Slack using CURL | |
*/ | |
protected function send($content, array $records) | |
{ | |
$msg = $content; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, "https://" . $this->account . ".slack.com/services/hooks/incoming-webhook?token=" . $this->token); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
$payload = json_encode( | |
array( | |
"channel" => $this->channel, | |
"username" => $this->username, | |
"text" => $msg, | |
"icon_url" => $this->icon | |
) | |
); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload ); | |
curl_exec($ch); | |
curl_close($ch); | |
} | |
} |
Great! ✨
(I guess that line n°54 (and 63) is useless.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes. Worked for me.
+1 for place this handler to packagist