Simple logging with PHP and Slack

Rich Barrett
2 min readSep 8, 2020

If you’ve not been living under a rock in recent years then you’ll probably have heard of Slack, a great tool for collaboration between distributed teams.

It comes with lots of useful features, some of which make it a great solution for logging events from your PHP applications. Out of the box, Slack has:

  • Channels: so you can easily separate log messages for different projects.
  • Mentions: so you can get push notifications to your computer or mobile device if something requires your attention.
  • A powerful search feature to help you search for log messages.

Step 1: Install a composer package to help do the interaction with Slack.

composer require maknz/slack

Step 2: Create an Incoming Webhook in Slack so we can post messages to it.

You can configure the “Incoming webhooks” app in Slack, follow steps 1–3 in the “Getting Started” section here:

The end result should be a URL (that you need to keep secret) that will look something like this:

https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

Good practice would suggest you should store this URL somewhere safe, like as an environment file, rather than hard code it or keep it in Version Control.

Step 3: Send some log messages to Slack!

The most basic implementation looks like this:

// Replace this with your Incoming Webhook URL
$webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
$client = new Maknz\Slack\Client($webhook_url, $settings);
$client->send('Hello world');

Optional: More sophisticated messages.

In most instances I use a simple function like the example below.

It allows you to use mentions and I configure the channel to send me a push notification on my phone if my name is mentioned in the channel. I can then be alerted to any urgent issues, even if I’m away from the computer.

function log_to_slack($config, $message) {

$settings['username'] = $config['username'];
$settings['link_names'] = true;
$client = new Maknz\Slack\Client($config['webhook_url'], $settings);
$client->send($message);

}
$config['username'] = 'My App';
$config['webhook_url'] = 'https://my.webhook.url.com';
log_to_slack($config, '@rich hello world');

You can download my example code here:

https://richbarrett.co.uk/medium/log_to_slack.zip

More examples:

You can do lots more with this package, such as post links and embed images among other media. See the examples here: https://github.com/maknz/slack

Extra reading:

Take a look at PHP’s register_shutdown_function to see how you can incorporate the above to log uncaught exceptions and other PHP level errors.

--

--

Rich Barrett

I’m a tech entrepreneur with a logistics tech, e-commerce, shipping & fulfilment background. UK Based. 🇬🇧🏴󠁧󠁢󠁷󠁬󠁳󠁿