Skip to content

Instantly share code, notes, and snippets.

@egruz
Last active July 17, 2016 15:24
Show Gist options
  • Save egruz/8855636 to your computer and use it in GitHub Desktop.
Save egruz/8855636 to your computer and use it in GitHub Desktop.
Monolog Slack Handler
<?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 <graham@webplace.com.au>
*
*/
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);
}
}
@dimti
Copy link

dimti commented Jun 23, 2014

Yes. Worked for me.
+1 for place this handler to packagist

@cyrilf
Copy link

cyrilf commented Apr 21, 2015

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