LaravelでSlack通知するためにFacadeを設定したり色々ややこしいことをしている記事があるが、Laravelには標準でSlack通知できる機能が備わっています。便利。
手順
1 . Slackの Webhook URLを発行
https://api.slack.com/apps
2 . .env
に以下を追加
LOG_SLACK_WEBHOOK_URL="1.で発行したURL"
LOG_SLACK_USERNAME="Hello Slack"
LOG_LEVEL="debug"
LOG_STACK=single,slack
3 . php artisan config:clear
で .env の設定更新
4 . src/config/slack.php
を作成し、以下のように追加
<?php
return [
'webhook_url' => env('LOG_SLACK_WEBHOOK_URL', ''),
'sender_name' => env('LOG_SLACK_USERNAME', ''),
'level' => env('LOG_LEVEL', 'debug'),
];
5 . src/config/logging.php
の該当箇所を以下のように変更
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
// ......
'slack' => [
'driver' => 'slack',
'url' => config('app.slack.webhook_url'),
'username' => config('app.slack.sender_name'),
'level' => config('app.slack.level'),
'emoji' => '',
'replace_placeholders' => true,
],
6 . 呼び出す
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Log;
Route::get('/slack', function (Request $request) {
Log::info('Hello!');
});
補足
slack app で作成したアプリの Webhook URL ではアイコンを設定することはできない
Making it fancy with advanced formatting/Sending messages using incoming webhooks
の末尾に書いている。
アプリアイコンが表示される。
You cannot override the default channel (chosen by the user who installed your app), username, or icon when you're using incoming webhooks to post messages. Instead, these values will always inherit from the associated Slack app configuration.
.env で設定しているLOG_LEVEL
が、src/config/logging.php
の syslog.level
と slack.level
の高い方より低く設定していると、Slackに出力されない
ログレベルは、
(高)emergency、alert、critical、error、warning、notice、info、debug(低)
という順番になっている。両方debugに設定するとどんなlevelでも出力される。
# 設定例
# .envで設定したLOG_LEVELがそれぞれのLevelでSlack出力されるか
(高) syslog.level slack.level .env/LOG_LEVEL
emergency 出力される
alert 出力される
critical syslog 出力される
--------------------------------------------------------------
error slack 出力されない
warning 出力されない
notice 出力されない
info 出力されない
debug 出力されない
(低)