slack-logs
v3.0.5
Published
slack-logs
Maintainers
Readme
Slack Log Package
Description
This package provides a simple and efficient way to log messages directly to Slack from your Node.js applications. Utilizing Slack's Incoming Webhooks, it allows for real-time notifications and logging of critical events, errors, or any custom messages you choose to send to your Slack channel.
Features
- Easy integration with Slack via Incoming Webhooks.
- Supports custom messages with dynamic data.
- Validates Slack webhook URLs before attempting to send messages.
- Asynchronous logging with async/await support.
- Configurable to fit various logging needs.
Installation
- Install the package using npm:
npm install slack-logs- Or using yarn:
yarn add slack-logsDemo
Try payload experiments here:
Configuration:
Before you start, ensure you have created an Incoming Webhook in Slack and have the webhook URL ready. For more information on setting up Incoming Webhooks in Slack, visit Slack's API documentation.
Usage
Here is a basic example of how to use the Slack Log package to send a message to your Slack channel:
Option 1: Use slackLogConfig(...)
import { slack, slackLogConfig } from "slack-logs";
or
const { slack, slackLogConfig } = require('slack-logs');
slackLogConfig({
webhookUrl: "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
enableAlerts: true,
});
/*Slack Notification with default format*/
slack.log("Data", [{ title: "1yes!" }]);
slack.log("Data", { title: "2yes!" });
slack.log("Data", "Hello world!");
/*Slack Notification with block format*/
const payload = [
{ title: "Title 1", value: "1234" },
{ title: "Title 2", value: 123 },
{ title: "Title 3", value: { id: 12 } },
{ title: "Title 3", value: [{ id: 12 }] },
];
slack.logBlockMessage("Validation Message!", payload);
slackLogConfig(...) rules:
webhookUrlandenableAlertsare both required- if
slackLogConfig(...)is used, env values are ignored for both fields slackLogConfig(...)does not ask for values interactively
Required Slack webhook setup
- credential required:
Incoming Webhook URL - URL format:
https://hooks.slack.com/services/... - where to find it: Slack App Settings ->
Incoming Webhooks->Webhook URLs for Your Workspace - enable
Incoming Webhooksfirst in the app settings - each webhook URL is tied to one Slack channel
- if you need different channels, create separate webhook URLs or use
slackbot
Create the Slack app / webhook if you don't have one
- Go to
https://api.slack.com/apps - Click
Create New App - Select
From scratch - Enter the app name and choose the workspace
- Open
Incoming Webhooks - Turn on
Activate Incoming Webhooks - Click
Add New Webhook to Workspace - Select the Slack channel
- Click
Allow - Copy the webhook URL from
Webhook URLs for Your Workspace - Use it in
slackLogConfig({ webhookUrl: "..." })orSLACK_WEBHOOK_URL
Option 2: Use environment variables
Use env values only when slackLogConfig(...) is not called.
.env 🚨
...
# Slack Webhook URL for sending logs and notifications.
# Replace with your actual webhook URL.
SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
# Optional field.
# If not defined, logs are sent by default.
# true / True / TRUE sends logs.
# false / False / FALSE skips logs.
ENABLE_SLACK_LOGS=true
...ENABLE_SLACK_LOGS behavior:
- if not defined, default is
true true,"true","True"and any case variation send logsfalse,"false","False"and any case variation do not send logs- any other value is treated as
false
Webhook validation
Expected format:
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXXIf webhook URL format is invalid, package logs a console error and skips sending.
/*Slack Notification with colored block format*/
import { LogLevel, slack } from "slack-logs";
const payload = [
{ title: "Title 1", value: "1234" },
{ title: "Title 2", value: 123 },
{ title: "Title 3", value: { id: 12 } },
{ title: "Title 3", value: [{ id: 12 }] },
];
slack.logBlockMessage("Validation Message!", payload);
// Or
slack.logBlockMessage("Validation Message!", payload, LogLevel.DEFAULT);
// Or
slack.logBlockMessage("Validation Message!", payload, LogLevel.ERROR);
// Or
slack.logBlockMessage("Validation Message!", payload, LogLevel.INFO);
// Or
slack.logBlockMessage("Validation Message!", payload, LogLevel.SUCCESS);
// Or
slack.logBlockMessage("Validation Message!", payload, LogLevel.WARN);
Sample code with output:
Sample 1:
import { slack } from "slack-logs";.
slack.log("Data Log with bold", "Here is *BOLD* message");
slack.log("Highlight Log", "`Message`");
slack.log("Emoji :rocket: Log", "Yeah :female-technologist::skin-tone-2:");
slack.log("Object Log", {id:"123", value:"Lorem Impulse"});
Sample 2:
import { LogLevel, slack } from "slack-logs";.
const payload = [
{ title: "Title 1", value: "1234" },
{ title: "Title 2", value: 123 },
{ title: "Title 3", value: { id: 12 } },
{ title: "Title 4", value: [{ id: 12 }] },
];
slack.logBlockMessage("Custom Logs!", payload);
slack.logBlockMessage("Some Information Logs!", payload, LogLevel.INFO);
slack.logBlockMessage("Critical Alert!", payload, LogLevel.ERROR);
Sample 3:
import { LogLevel, slack } from "slack-logs";.
const payload = [
{ title: "Event Name", value: "directMessage" },
{
title: "`to_user` Validation",
value: "Message 'to_user' is required! Current value is null",
},
];
slack.logBlockMessage(`Validation failure on "development" server`, payload, LogLevel.WARN);
Sample 3:
import { LogLevel, slack } from "slack-logs";.
const title =
":rotating_light: Error processing message failure on 'local' server :rotating_light:";
const payload = [
{ title: "Event Name", value: "directMessage" },
{ title: "`error`", value: {} },
];
slack.logBlockMessage(title, payload, LogLevel.ERROR);
Contributing
Contributions are welcome! If you have a feature request, bug report, or a pull request, please open an issue or submit a PR on the GitHub repository
License:
This package is licensed under the MIT License - see the LICENSE file for details.
Raw body
Use slack.rawBody(...) when you want to send a custom Slack payload as-is.
import { slack } from "slack-logs";
const payload = {
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: "Hello from custom payload",
},
},
{
type: "divider",
},
{
type: "actions",
elements: [
{
type: "button",
text: {
type: "plain_text",
text: "Open",
emoji: true,
},
value: "click_me_123",
url: "https://google.com",
},
],
},
],
};
slack.rawBody(payload);slack.rawBody(...) expects a plain object payload like:
{
"blocks": [...]
}If payload is invalid or sending fails, it logs a console error.
Slack Bot
Use slackbot when you want the same logging helpers with bot-token based multi-channel support.
Configuration
import { slackbot, slackBotConfig } from "slack-logs";
or
const { slackbot, slackBotConfig } = require("slack-logs");
slackBotConfig({
botToken: "xoxb-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX",
defaultChannelId: "C0123456789",
enableAlerts: true,
});slackBotConfig(...) rules:
botTokenandenableAlertsare requireddefaultChannelIdis optional if you passchannelIdin method calls- if
defaultChannelIdis not set in config, package falls back toSLACK_BOT_DEFAULT_CHANNEL_ID
Required Slack app setup
- token required:
Bot User OAuth Access Token - token format:
xoxb-... - where to find it: Slack App Settings ->
OAuth & Permissions->Bot User OAuth Access Token - important: the token appears only after you click
Install to Workspace - add scopes under
OAuth & Permissions->Bot Token Scopes - required scope:
chat:write - optional scope:
chat:write.publicif you want to post in public channels without inviting the app first - do not use
User Token Scopes - do not use app-level tokens (
xapp-...) for this package - if the app is not in a channel, invite it first unless you added
chat:write.public
Environment variables
Use env values only when slackBotConfig(...) is not called.
.env 🚨
...
SLACK_BOT_TOKEN="xoxb-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX"
SLACK_BOT_DEFAULT_CHANNEL_ID="C0123456789"
# Optional field.
# If not defined, logs are sent by default.
# true / True / TRUE sends logs.
# false / False / FALSE skips logs.
ENABLE_SLACK_BOT_LOGS=true
...Create the Slack app if you don't have one
- Go to
https://api.slack.com/apps - Click
Create New App - Select
From scratch - Enter the app name and choose the workspace
- Open
OAuth & Permissions - Under
Bot Token Scopes, addchat:write - Optional: add
chat:write.public - Click
Install to Workspace - Copy the
Bot User OAuth Access Token(xoxb-...) - Use it in
slackBotConfig({ botToken: "xoxb-..." })orSLACK_BOT_TOKEN
Methods
slackbot.log(label, data, channelId?);
slackbot.logBlockMessage(label, payload, errorType?, channelId?);
slackbot.rawBody(payload, channelId?);slackbot.log(...)
slackbot.log(...) uses the same payload format as slack.log(...), so the output style is the same.
import { slackbot } from "slack-logs";
slackbot.log("Data Log with bold", "Here is *BOLD* message", "C0123456789");
slackbot.log("Highlight Log", "`Message`", "C0123456789");
slackbot.log("Emoji :rocket: Log", "Yeah :female-technologist::skin-tone-2:");
slackbot.log("Object Log", {id:"123", value:"Lorem Impulse"});
slackbot.logBlockMessage(...)
slackbot.logBlockMessage(...) uses the same payload format as slack.logBlockMessage(...), so the same output examples apply.
import { LogLevel, slackbot } from "slack-logs";
const payload = [
{ title: "Title 1", value: "1234" },
{ title: "Title 2", value: 123 },
{ title: "Title 3", value: { id: 12 } },
{ title: "Title 4", value: [{ id: 12 }] },
];
slackbot.logBlockMessage("Custom Logs!", payload, LogLevel.DEFAULT, "C0123456789");
slackbot.logBlockMessage("Some Information Logs!", payload, LogLevel.INFO);
slackbot.logBlockMessage("Critical Alert!", payload, LogLevel.ERROR);
slackbot.rawBody(...)
Use slackbot.rawBody(...) when you want to send a custom Slack payload with an optional channelId.
import { slackbot } from "slack-logs";
const payload = {
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: "Hello from custom payload",
},
},
{
type: "divider",
},
{
type: "actions",
elements: [
{
type: "button",
text: {
type: "plain_text",
text: "Open",
emoji: true,
},
value: "click_me_123",
url: "https://google.com",
},
],
},
],
};
slackbot.rawBody(payload, "C0123456789");slackbot.rawBody(...) expects a plain object payload like:
{
"blocks": [...]
}If payload is invalid or sending fails, it logs a console error.
