## 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-logs
```

### Demo

[StackBlitz Demo](https://stackblitz.com/edit/stackblitz-starters-minuqbqu?file=index.js)

<!-- ![Slack Logs Demo](./images/demo-preview.png) -->

### Try payload experiments here:

[Slack Block Kit Builder](https://app.slack.com/block-kit-builder/T9D4GM7L0)

### 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.](https://api.slack.com/messaging/webhooks)

### 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:

- `webhookUrl` and `enableAlerts` are both required
- if `slackLogConfig(...)` is used, env values are ignored for both fields
- `slackLogConfig(...)` does not ask for values interactively

#### 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 logs
- `false`, `"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/XXXXXXXXXXXXXXXXXXXXXXXX
```

If 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 Image](https://i.imgur.com/ucAnAiJ.png)

#### 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 Image](https://i.imgur.com/Ohlktzr.png)

#### 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 Image](https://i.imgur.com/yncdwGJ.png)

#### 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);
```

![Sample Image](https://i.imgur.com/XszvEEw.png)

### 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.
