Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

winston-slack-webhook-transport

TheAppleFreak121kMIT2.3.6TypeScript support: included

A Slack transport for Winston 3 that logs to a channel via webhooks.

winston, transport, slack, log, logger, logging, webhook

readme

winston-slack-webhook-transport

A Slack transport for Winston 3+ that logs to a channel via webhooks.

Continuous Integration npm version downloads

Installation

npm install winston winston-slack-webhook-transport

Usage

Set up with transports

const winston = require("winston");
const SlackHook = require("winston-slack-webhook-transport");

const logger = winston.createLogger({
    level: "info",
    transports: [
        new SlackHook({
            webhookUrl: "https://hooks.slack.com/services/xxx/xxx/xxx"
        })
    ]
});

logger.info("This should now appear on Slack");

Set up by adding

const winston = require("winston");
const SlackHook = require("winston-slack-webhook-transport");

const logger = winston.createLogger({});

logger.add(new SlackHook({ webhookUrl: "https://hooks.slack.com/services/xxx/xxx/xxx" }));

Options

  • webhookUrl REQUIRED - Slack incoming webhook URL. Follow steps 1 through 3 at this link to create a new webhook if you don't already have one.
  • formatter - Custom function to format messages with. This function accepts the info object (see Winston documentation) and must return an object with at least one of the following three keys: text (string), attachments (array of attachment objects), blocks (array of layout block objects). These will be used to structure the format of the logged Slack message. By default, messages will use the format of [level]: [message] with no attachments or layout blocks. A value of false can also be returned to prevent a message from being sent to Slack.
  • level - Level to log. Global settings will apply if left undefined.
  • unfurlLinks - Enables or disables link unfurling. (Default: false)
  • unfurlMedia - Enables or disables media unfurling. (Default: false)
  • mrkdwn - Enables or disables mrkdwn formatting within attachments or layout blocks (Default: false)
  • proxy - Allows specifying a proxy server that gets passed directly down to Axios (Default: undefined)
  • channel - Overrides the webhook's default channel. This should be a channel ID. (Default: undefined)
  • username - Overrides the webhook's default username. (Default: undefined)
  • iconEmoji - An emoji code string to use in place of the default icon. (Interchangeable with iconUrl) (Default: undefined)
  • iconUrl - An icon image URL string to use in place of the default icon. Interchangeable with iconEmoji. (Default: undefined)
  • emitAxiosErrors - Enables or disables emitting errors when Axios throws an error. This can occur if Slack returns a non-200 response code, such as 429 Too Many Requests. When disabled, Slack errors will be silently dropped, though if unhandled this can possibly lead to unexpected and transient crashes. Enable to handle those errors yourself. (Default: false)

Message formatting

winston-slack-webhook-transport supports the ability to format messages using Slack's message layout features. To do this, supply a custom formatter function that returns the requisite object structure to create the desired layout. You can use the Slack Block Kit Builder to quickly and easily prototype advanced layouts using Block Kit.

If for some reason you don't want to send a message to Slack, you can also return false to prevent the log message from being sent.

Formatters can also override the channel the message is posted to, username, and icon by defining the properties channel, username, iconEmoji, or iconUrl in the same object structure. These will override any options set in the transport constructor.

Note that if you're using Block Kit using either the attachments or blocks keys, the text parameter will function as a fallback for surfaces that do not support Block Kit, such as push notifications. It is recommended to include text when possible in these cases.

const winston = require("winston");
const SlackHook = require("winston-slack-webhook-transport");

const logger = winston.createLogger({
    level: "info",
    transports: [
        new SlackHook({
            webhookUrl: "https://hooks.slack.com/services/xxx/xxx/xxx",
            formatter: info => {
                return {
                    text: "This will function as a fallback for surfaces that don't support Block Kit, like IRC clients or mobile push notifications.",
                    blocks: [
                        {
                            type: "section",
                            text: {
                                type: "plain_text",
                                text: "You can pass more info to the formatter by supplying additional parameters in the logger call"
                            }
                        }
                    ],
                    attachments: [
                        {
                            text: "Or don't pass anything. That's fine too"
                        }
                    ]
                }
            }
        })
    ]
});

logger.info("Definitely try playing around with this.");

changelog

CHANGELOG

(all dates use the ISO-8601 format, which is YYYY/MM/DD)

2.3.6 (2024/11/12)

  • No changes have been made to the code in this release.
  • Updated dependencies so Dependabot would stop yelling at me.
  • Fixed link rot in README.md and slightly updated one of the code examples so it reads better.

2.3.5 (2024/3/21)

  • No changes have been made to the code in this release.
  • Updated dependencies.

2.3.4 (2024/1/10)

  • No changes have been made to the code in this release.
  • Updated dependencies, which closes Pull #32 in the process.
  • Updated copyright year in LICENSE.md

2.3.3 (2023/11/11)

  • No changes have been made to the code in this release.
  • Updated dependencies, which solves Pull #29 and Pull #30 while also closing Issue #31. Thanks @dvasilen!
  • Updated devcontainer.json to ensure the development environment is using the latest version of Node and NPM available.

2.3.2 (2023/5/10)

  • The SlackHookOptions type now extends TransportStreamOptions, properly this time. This change is courtesy of Pull #28. Thanks again @DominicRoyStang!
  • Deprecated v2.3.1 for the above reason. While v2.3.1 should not cause any issues for existing users and use cases, I'd rather not have a potentially buggy version in the wild.
  • Updated GitHub Actions to test against Node.js 16 and the latest available version, instead of just Node.js 16.

2.3.1 (2023/5/10)

  • The SlackHookOptions type now extends TransportStreamOptions. This change is courtesy of Pull #26. Thanks @DominicRoyStang!

2.3.0 (2023/4/5)

  • Added an option (emitAxiosErrors) to enable or disable emitting errors if Axios throws an error. Previously, if Axios returned an error for any reason, this would emit an error, which if unhandled would be treated as an unhandled exception. This includes potentially transient issues, such as if Slack would return an error for any reason, including API outages or 429 Too Many Requests errors. This option requires the user to explicitly opt into this behavior, and is false by default. This closes Issue #24. Thanks @jbojbo for bringing this to my attention!

    When I had initially added the code that would do that, I was under the impression this would log the Slack error to Winston itself as an error, but after rereading the relevant documentation I realized this was not the case.

  • Minor change to the log() function to make it an async function, which simplifies some minor aspects of unit testing. This should have no impact on using the transport within Winston.
  • Updated tests to check the error handling behavior.
  • Added new option to the type definitions.
  • Added a Prettier script and prettierrc.
  • Updated dependencies, and double checked to make sure everything continued to work this time.

2.2.3 (2023/3/3)

  • Fixed a bug preventing the ability to filter log messages in the formatter. This change is courtesy of Pull #23, which closes Issue #15 in the process. Thanks @ArturAralin and @jbojbo!
  • Updated copyright year in LICENSE. I need to automate this.

2.2.2 (2022/10/6)

  • Reverted axios dependency back to ^0.22.0 due to unforseen issues. This closes Issue #21.
  • Deprecated v2.2.0 and v2.2.1 for the above reason.

2.2.1 (2022/10/6)

  • Realized that I hadn't quite proofread the code in 2.2.0 as closely as I should have, and that it worked in a different way than I expected. Updated the code and documentation to reflect that you can override the properties in both the constructor as well as in the formatter to achieve the same result.

2.2.0 (2022/10/6)

2.1.0 (2021/10/4)

  • You can now return false in the formatter function to prevent the plugin from posting a message to Slack. This functionality is courtesy of Pull #14, which closes Issue #12 in the process. Thanks @iedmrc and @daxadal!
  • Updated documentation and typings to reflect the above change.
  • Removed Yarn as the package manager in favor of using NPM instead.
  • Set up Github Actions to simplify the process of updating the package on NPM in the future.
  • Updated copyright year in LICENSE. Probably should have done that about 10 months ago... ¯\(ツ)
  • Updated dependencies

2.0.0 (2020/8/14)

WARNING: This is a potentially BREAKING CHANGE.

  • BREAKING: Removed the channel, username, iconEmoji, and iconUrl properties from the constructor and typings. According to Slack, these properties cannot be overridden by webhooks so it makes no sense to include them and potentially confuse users. As per semantic versioning, I am bumping the version to 2.0.0 to prevent existing clients using these features from suddenly breaking unexpectedly. Nothing else about the code has been modified at this time.
  • Removed checks for the aforementioned properties in the tests.
  • Fixed link rot in README.md and added a little more detail to the package instructions.
  • Modified package.json to only bundle the files needed to use the package. Sorry about accidentally bloating the package size to over 2MB because I left the Yarn executable in...
  • Updated copyright year in LICENSE
  • Updated dependencies

1.2.5 (2020/7/29)

  • Updated dependencies
  • Updated gitignore to latest Node version
  • Fixed error in README.md (as per Pull #11). Thanks @zachweinberg!
  • Changed all tabs in README.md to spaces for a more unified presentation
  • Changed test script to not point directly at the Jest executable anymore
  • Added Yarn 2 files
  • Updated yarn.lock so that GitHub would stop yelling at me about lodash being out of date

1.2.4 (2020/5/7)

  • Updated yarn.lock so that GitHub would stop yelling at me about acorn being out of date

1.2.3 (2020/5/7)

  • Updated dependencies

1.2.2 (2020/5/7)

  • Fixed TypeScript declaration file (as per Pull #9). Thanks @dmitryyacenko and @xr!

1.2.1 (2020/2/28)

  • Fixed TypeScript declaration file (as per Issue #7). Thanks @FredericLatour!

1.2.0 (2020/2/14)

1.1.0 (2019/7/15)

  • Callback now triggers only after request completes (as per Pull #4). Thanks @iudelsmann!

1.0.1 (2019/6/21)

  • Updated dependencies

1.0.0 (2019/3/5)

WARNING - This is a BREAKING CHANGE.

  • Reworked the logger so it uses request instead of the much heavier Slack API.
  • Added support for the new Layout Blocks formatting option that Slack recently introduced.
  • Implemented formatter suggestion from Issue #2 to tidy up the logger calls.
  • Removed the old method of attaching attachments, also as a suggestion from Issue #2.