Skip to content

Instantly share code, notes, and snippets.

@ybelenko
Last active December 11, 2022 10:33
Show Gist options
  • Save ybelenko/bd18572aca7785e06fd23f21225bb50e to your computer and use it in GitHub Desktop.
Save ybelenko/bd18572aca7785e06fd23f21225bb50e to your computer and use it in GitHub Desktop.
Shell logging to Slack Webhook
#!/bin/bash
#######################################
# Send log message to Slack channel via Webhook.
#
# @author Yuriy Belenko <yura-bely@mail.ru>
# This functions requires jo package installed. https://github.com/jpmens/jo
#
# Originally developed as almost zero dependency(jo only) alternative of Slack Monolog PHP handler:
# https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/SlackWebhookHandler.php
#
# Ref to Slack webhook doc: https://api.slack.com/messaging/webhooks
# Globals:
# SLACK_WEBHOOK
# Arguments:
# $1 message
# $2 (optional) log level, eg DEBUG or code equivalent 100
# Returns:
# nothing if message has been sent, non-zero on error.
#######################################
function slack_log() {
local level='DEBUG' color='#e3e4e6' payload attachment log_level_field timestamp
timestamp=$(date +%s)
if [[ -z "${SLACK_WEBHOOK}" ]]; then
echo "Error: SLACK_WEBHOOK constant required for slack_log" >&2
return 1
fi
if [[ -z "$1" ]]; then
echo 'Error: at least one argument requred in slack_log()' >&2
return 1
fi
if [[ -n "$2" ]]; then
# log level specified
case "$2" in
DEBUG | 100)
level='DEBUG'
color='#e3e4e6'
;;
INFO | 200)
level='INFO'
color='good'
;;
NOTICE | 250)
level='NOTICE'
color='good'
;;
WARNING | 300)
level='WARNING'
color='warning'
;;
ERROR | 400)
level='ERROR'
color='danger'
;;
CRITICAL | 500)
level='CRITICAL'
color='danger'
;;
ALERT | 550)
level='ALERT'
color='danger'
;;
EMERGENCY | 600)
level='EMERGENCY'
color='danger'
;;
*)
echo 'Error: Invalid log level in slack_log()' >&2
return 1
;;
esac
fi
log_level_field=$(jo title="Level" value="${level}" short@0)
attachment=$(jo title="Message" fallback="$1" text="$1" color="${color}" fields[]="${log_level_field}" mrkdwn_in="fields" ts="${timestamp}")
payload=$(jo attachments[]="${attachment}")
curl --request POST \
--url "${SLACK_WEBHOOK}" \
--header 'Content-type: application/json' \
--data "${payload}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment