├── .github └── workflows │ └── main.yml ├── .gitignore ├── README.md ├── package.json ├── src └── index.ts ├── test └── bunyan-slack.test.ts ├── tsconfig.json └── yarn.lock /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push] 3 | jobs: 4 | build: 5 | name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }} 6 | 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | node: ['14.x', '16.x', '18.x'] 11 | os: [ubuntu-latest, windows-latest, macOS-latest] 12 | 13 | steps: 14 | - name: Checkout repo 15 | uses: actions/checkout@v2 16 | 17 | - name: Use Node ${{ matrix.node }} 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: ${{ matrix.node }} 21 | 22 | - name: Install deps and build (with cache) 23 | uses: bahmutov/npm-install@v1 24 | 25 | - name: Lint 26 | run: yarn lint 27 | 28 | - name: Test 29 | run: yarn test --ci --coverage --maxWorkers=2 30 | 31 | - name: Build 32 | run: yarn build 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | dist 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bunyan-slack 2 | 3 | [![bunyan-slack](http://img.shields.io/npm/v/bunyan-slack.svg?style=flat-square)](https://www.npmjs.com/package/bunyan-slack) 4 | [![bunyan-slack](http://img.shields.io/npm/dm/bunyan-slack.svg?style=flat-square)](https://www.npmjs.com/package/bunyan-slack) 5 | [![bunyan-slack](http://img.shields.io/npm/l/bunyan-slack.svg?style=flat-square)](https://www.npmjs.com/package/bunyan-slack) 6 | 7 | **Bunyan stream for Slack chat integration** 8 | 9 | First install bunyan... 10 | 11 | ``` 12 | npm install bunyan 13 | ``` 14 | 15 | Then install bunyan-slack 16 | 17 | ``` 18 | npm install bunyan-slack 19 | ``` 20 | 21 | ## Basic Setup 22 | 23 | ```javascript 24 | const bunyan = require('bunyan'); 25 | const BunyanSlack = require('bunyan-slack'); 26 | 27 | const log = bunyan.createLogger({ 28 | name: 'myApp', 29 | streams: [ 30 | { 31 | type: 'raw', 32 | stream: new BunyanSlack({ 33 | webhookUrl: 'your_webhook_url', 34 | channel: '#your_channel', 35 | username: 'your_username', 36 | }), 37 | }, 38 | ], 39 | level: 'error', 40 | }); 41 | 42 | log.error('hello bunyan slack'); 43 | ``` 44 | 45 | You can also pass an optional error handler. 46 | 47 | > Specify a Slack channel by name with `"channel": "#other-channel"`, or send a Slackbot message to a specific user with `"channel": "@username"`. 48 | 49 | ```javascript 50 | const stream = new BunyanSlack({ 51 | webhookUrl: 'your_webhook_url', 52 | channel: '#your_channel', 53 | username: 'your_username', 54 | onError: function(error) { 55 | console.log(error); 56 | }, 57 | }); 58 | ``` 59 | 60 | ## Custom Formatters 61 | 62 | By default the logs are formatted like so: `[LOG_LEVEL] message`, unless you specify a `customFormatter` function. 63 | 64 | ```javascript 65 | const log = bunyan.createLogger({ 66 | name: 'myApp', 67 | stream: new BunyanSlack({ 68 | webhookUrl: 'your_webhook_url', 69 | channel: '#your_channel', 70 | username: 'your_username', 71 | customFormatter: function(record, levelName) { 72 | return { text: '[' + levelName + '] ' + record.msg }; 73 | }, 74 | }), 75 | level: 'error', 76 | }); 77 | ``` 78 | 79 | ## Custom Formatter Options 80 | 81 | > Check the [slack docs](https://api.slack.com/incoming-webhooks) for custom formatter options. 82 | 83 | ### Putting it all together 84 | 85 | ```javascript 86 | const bunyan = require('bunyan'); 87 | const BunyanSlack = require('bunyan-slack'); 88 | 89 | const log = bunyan.createLogger({ 90 | name: 'myapp', 91 | stream: new BunyanSlack({ 92 | webhookUrl: 'your_webhook_url', 93 | iconUrl: 'your_icon_url', 94 | channel: '#your_channel', 95 | username: 'your_username', 96 | iconEmoji: ':scream_cat:', 97 | customFormatter: function(record, levelName) { 98 | return { 99 | attachments: [ 100 | { 101 | fallback: 'Required plain-text summary of the attachment.', 102 | color: '#36a64f', 103 | pretext: 'Optional text that appears above the attachment block', 104 | author_name: 'Seth Pollack', 105 | author_link: 'http://sethpollack.net', 106 | author_icon: 'http://www.gravatar.com/avatar/3f5ce68fb8b38a5e08e7abe9ac0a34f1?s=200', 107 | title: 'Slack API Documentation', 108 | title_link: 'https://api.slack.com/', 109 | text: 'Optional text that appears within the attachment', 110 | fields: [ 111 | { 112 | title: 'We have a new ' + levelName + ' log', 113 | value: ':scream_cat: ' + record.msg, 114 | short: true, 115 | }, 116 | ], 117 | }, 118 | ], 119 | }; 120 | }, 121 | }), 122 | level: 'error', 123 | }); 124 | ``` 125 | 126 | --- 127 | 128 | This library was adapted from [winston-bishop-slack](https://github.com/lapwinglabs/winston-bishop-slack) 129 | 130 | The MIT License 131 | Copyright (c) 2015 [QualityBath.com](https://www.qualitybath.com/) 132 | 133 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 134 | 135 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 136 | 137 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 138 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0", 3 | "name": "bunyan-slack", 4 | "module": "dist/bunyan-slack.esm.js", 5 | "main": "dist/index.js", 6 | "typings": "dist/index.d.ts", 7 | "license": "MIT", 8 | "files": [ 9 | "dist", 10 | "src" 11 | ], 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/qualitybath/bunyan-slack" 15 | }, 16 | "keywords": [ 17 | "logging", 18 | "slack", 19 | "bunyan", 20 | "log", 21 | "logger", 22 | "transport", 23 | "stream" 24 | ], 25 | "bugs": { 26 | "url": "https://github.com/qualitybath/bunyan-slack/issues" 27 | }, 28 | "engines": { 29 | "node": ">=14" 30 | }, 31 | "scripts": { 32 | "start": "tsdx watch", 33 | "build": "tsdx build", 34 | "test": "tsdx test", 35 | "lint": "tsdx lint", 36 | "prepare": "tsdx build" 37 | }, 38 | "husky": { 39 | "hooks": { 40 | "pre-commit": "tsdx lint" 41 | } 42 | }, 43 | "prettier": { 44 | "printWidth": 120, 45 | "singleQuote": true, 46 | "trailingComma": "es5" 47 | }, 48 | "devDependencies": { 49 | "@slack/types": "^2.7.0", 50 | "@types/bunyan": "^1.8.8", 51 | "bunyan": "^1.8.15", 52 | "husky": "^8.0.1", 53 | "tsdx": "^0.14.1", 54 | "tslib": "^2.4.0", 55 | "typescript": "^4.7.4" 56 | }, 57 | "dependencies": { 58 | "got": "11.8.5" 59 | } 60 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import util from 'util'; 2 | import got from 'got'; 3 | import { MessageAttachment } from '@slack/types'; 4 | 5 | enum ERecordLevel { 6 | trace = 10, 7 | debug = 20, 8 | info = 30, 9 | warn = 40, 10 | error = 50, 11 | fatal = 60, 12 | } 13 | 14 | const noop = () => {}; 15 | function defaultFormatter( 16 | record: T, 17 | levelName: keyof typeof ERecordLevel 18 | ) { 19 | return { 20 | text: util.format('[%s] %s', levelName.toUpperCase(), record.msg), 21 | }; 22 | } 23 | 24 | export default class BunyanSlack { 25 | webhookUrl: string; 26 | channel?: string; 27 | username?: string; 28 | iconUrl?: string; 29 | iconEmoji?: string; 30 | customFormatter: ( 31 | record: T, 32 | levelName: keyof typeof ERecordLevel 33 | ) => { text: string } | { attachments: MessageAttachment[] }; 34 | onError: (err: unknown) => void; 35 | 36 | constructor( 37 | options: Omit, 'write' | 'customFormatter' | 'onError'> & { 38 | customFormatter?: BunyanSlack['customFormatter']; 39 | onError?: BunyanSlack['onError']; 40 | } 41 | ) { 42 | if (!options.webhookUrl) { 43 | throw new Error('Webhook url required'); 44 | } 45 | this.webhookUrl = options.webhookUrl; 46 | this.channel = options.channel; 47 | this.username = options.username; 48 | this.iconUrl = options.iconUrl; 49 | this.iconEmoji = options.iconEmoji; 50 | this.customFormatter = options.customFormatter || defaultFormatter; 51 | this.onError = options.onError || noop; 52 | } 53 | 54 | async write(record: Object) { 55 | try { 56 | const parsedRecord = typeof record === 'string' ? (JSON.parse(record) as T) : (record as T); 57 | const levelName = ERecordLevel[parsedRecord.level] as keyof typeof ERecordLevel; 58 | 59 | const message = this.customFormatter(parsedRecord, levelName); 60 | const body = { 61 | channel: this.channel, 62 | username: this.username, 63 | icon_url: this.iconUrl, 64 | icon_emoji: this.iconEmoji, 65 | ...message, 66 | }; 67 | 68 | await got.post(this.webhookUrl, { json: body }); 69 | } catch (err) { 70 | this.onError(err); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /test/bunyan-slack.test.ts: -------------------------------------------------------------------------------- 1 | import Bunyan from 'bunyan'; 2 | import got from 'got'; 3 | import BunyanSlack from '../src'; 4 | 5 | describe('Bunyan Slack', () => { 6 | describe('constructor', function() { 7 | it('should require a webhook', function() { 8 | expect(function() { 9 | new BunyanSlack({} as any); 10 | }).toThrow(new Error('Webhook url required')); 11 | }); 12 | 13 | it('should set options', function() { 14 | const spy = jest.spyOn(got, 'post').mockReturnValueOnce({ success: true } as any); 15 | 16 | const options = { 17 | webhookUrl: 'mywebhookurl', 18 | channel: '#bunyan-slack', 19 | username: '@sethpollack', 20 | iconEmoji: ':smile:', 21 | iconUrl: 'http://www.gravatar.com/avatar/3f5ce68fb8b38a5e08e7abe9ac0a34f1?s=200', 22 | }; 23 | 24 | const log = Bunyan.createLogger({ 25 | name: 'myapp', 26 | streams: [{ type: 'raw', stream: new BunyanSlack(options) }], 27 | level: 'info', 28 | }); 29 | 30 | const logText = 'foobar'; 31 | log.info(logText); 32 | expect(spy).toHaveBeenCalledWith(options.webhookUrl, { 33 | json: { 34 | channel: options.channel, 35 | username: options.username, 36 | icon_url: options.iconUrl, 37 | icon_emoji: options.iconEmoji, 38 | text: `[INFO] ${logText}`, 39 | }, 40 | }); 41 | }); 42 | 43 | it('should use the custom formatter', function() { 44 | const spy = jest.spyOn(got, 'post').mockReturnValueOnce({ success: true } as any); 45 | 46 | const options = { 47 | webhookUrl: 'mywebhookurl', 48 | customFormatter: (record: any, levelName: string) => { 49 | return { 50 | attachments: [ 51 | { 52 | fallback: 'Required plain-text summary of the attachment.', 53 | color: '#36a64f', 54 | pretext: 'Optional text that appears above the attachment block', 55 | author_name: 'Seth Pollack', 56 | author_link: 'http://sethpollack.net', 57 | author_icon: 'http://www.gravatar.com/avatar/3f5ce68fb8b38a5e08e7abe9ac0a34f1?s=200', 58 | title: 'Slack API Documentation', 59 | title_link: 'https://api.slack.com/', 60 | text: 'Optional text that appears within the attachment', 61 | fields: [ 62 | { 63 | title: `We have a new ${levelName} log`, 64 | value: `:scream_cat: ${record.msg}`, 65 | short: true, 66 | }, 67 | ], 68 | }, 69 | ], 70 | }; 71 | }, 72 | }; 73 | 74 | const log = Bunyan.createLogger({ 75 | name: 'myapp', 76 | streams: [{ type: 'raw', stream: new BunyanSlack(options) }], 77 | level: 'info', 78 | }); 79 | 80 | const logText = 'foobar'; 81 | log.info(logText); 82 | expect(spy).toHaveBeenCalledWith(options.webhookUrl, { 83 | json: { 84 | attachments: [ 85 | { 86 | fallback: 'Required plain-text summary of the attachment.', 87 | color: '#36a64f', 88 | pretext: 'Optional text that appears above the attachment block', 89 | author_name: 'Seth Pollack', 90 | author_link: 'http://sethpollack.net', 91 | author_icon: 'http://www.gravatar.com/avatar/3f5ce68fb8b38a5e08e7abe9ac0a34f1?s=200', 92 | title: 'Slack API Documentation', 93 | title_link: 'https://api.slack.com/', 94 | text: 'Optional text that appears within the attachment', 95 | fields: [ 96 | { 97 | title: 'We have a new info log', 98 | value: ':scream_cat: foobar', 99 | short: true, 100 | }, 101 | ], 102 | }, 103 | ], 104 | }, 105 | }); 106 | }); 107 | }); 108 | 109 | describe('error handler', function() { 110 | it('should use the custom error handler', function() { 111 | const onError = jest.fn(); 112 | 113 | const options = { 114 | webhookUrl: 'mywebhookurl', 115 | customFormatter: (record: any) => { 116 | return record.foo(); 117 | }, 118 | onError, 119 | }; 120 | 121 | const log = Bunyan.createLogger({ 122 | name: 'myapp', 123 | streams: [{ type: 'raw', stream: new BunyanSlack(options) }], 124 | level: 'info', 125 | }); 126 | log.info('foobar'); 127 | expect(onError).toHaveBeenCalledTimes(1); 128 | }); 129 | }); 130 | }); 131 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": ["src", "types"], 4 | "compilerOptions": { 5 | "module": "esnext", 6 | "lib": ["dom", "esnext"], 7 | "importHelpers": true, 8 | // output .d.ts declaration files for consumers 9 | "declaration": true, 10 | // output .js.map sourcemap files for consumers 11 | "sourceMap": true, 12 | // match output dir to input dir. e.g. dist/index instead of dist/src/index 13 | "rootDir": "./src", 14 | // stricter type-checking for stronger correctness. Recommended by TS 15 | "strict": true, 16 | // linter checks for common issues 17 | "noImplicitReturns": true, 18 | "noFallthroughCasesInSwitch": true, 19 | // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative 20 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | // use Node's module resolution algorithm, instead of the legacy TS one 23 | "moduleResolution": "node", 24 | // transpile JSX to React.createElement 25 | "jsx": "react", 26 | // interop between ESM and CJS modules. Recommended by TS 27 | "esModuleInterop": true, 28 | // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS 29 | "skipLibCheck": true, 30 | // error out if import and file system have a casing mismatch. Recommended by TS 31 | "forceConsistentCasingInFileNames": true, 32 | // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` 33 | "noEmit": true 34 | } 35 | } 36 | --------------------------------------------------------------------------------