├── .github └── workflows │ └── publish.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── index.d.ts ├── index.d.ts.map ├── index.js ├── package-lock.json ├── package.json └── tsconfig.json /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | # Build binaries for macOS and Linux, publish Node.js packages, create release 2 | name: build-publish-release 3 | 4 | on: 5 | push: 6 | tags: 7 | - 'v*.*.*' 8 | 9 | jobs: 10 | publish-node-packages: 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: read 14 | packages: write 15 | 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2 19 | - name: Setup 20 | uses: actions/setup-node@v2 21 | with: 22 | node-version: '16.x' 23 | registry-url: 'https://registry.npmjs.org' 24 | 25 | - name: Build and publish to npm registry 26 | run: | 27 | npm ci 28 | npm publish --access public 29 | env: 30 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 31 | - uses: actions/setup-node@v2 32 | with: 33 | node-version: '16.x' 34 | registry-url: 'https://npm.pkg.github.com' 35 | scope: "@baselime" 36 | 37 | - run: echo "registry=https://npm.pkg.github.com/@baselime" >> .npmrc 38 | 39 | - name: Publish to GitHub registry 40 | continue-on-error: true 41 | run: npm publish 42 | env: 43 | NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | notify-community: 45 | needs: [publish-node-packages] 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: Checkout 49 | uses: actions/checkout@v2 50 | - name: Get version from tag 51 | id: tag_name 52 | run: | 53 | echo ::set-output name=current_version::${GITHUB_REF#refs/tags/v} 54 | - name: Post to the community Slack channel 55 | uses: slackapi/slack-github-action@v1.23.0 56 | with: 57 | channel-id: 'C04KT9JNRHS' 58 | payload: | 59 | { 60 | "text": "[Release] Baselime Node Logger v${{ steps.tag_name.outputs.current_version }}", 61 | "blocks": [ 62 | { 63 | "type": "section", 64 | "text": { 65 | "type": "mrkdwn", 66 | "text": "*[Release] Baselime Node LoggerCLI v${{ steps.tag_name.outputs.current_version }}*" 67 | } 68 | }, 69 | { 70 | "type": "section", 71 | "text": { 72 | "type": "mrkdwn", 73 | "text": "" 74 | } 75 | } 76 | ] 77 | } 78 | env: 79 | SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | 6 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). 7 | 8 | # [0.2.2] 29-08-2023# 9 | 10 | - fix middy log level (Thank you @Björn) 11 | ## [0.1.7] 6-09-2023 12 | ### Changed 13 | - Improved typing for wrap 14 | - Improved error handling in log 15 | - Fixed level -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Baselime 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## AWS Lambda Logging Library for Node.js 2 | 3 | [![Documentation][docs_badge]][docs] [![License][license_badge]][license] 4 | 5 | The library offers a straightforward logging solution for Node.js-based AWS 6 | Lambda functions, requiring no external dependencies. 7 | 8 | ```javascript 9 | const { logger } = require("@baselime/lambda-logger"); 10 | 11 | logger.info("This is an informational message", { 12 | operation: "copy-paste-replace", 13 | count: 9000, 14 | }); 15 | ``` 16 | 17 | The library provides an object that includes four logging functions - `info`, 18 | `warn`, `debug`, and `error` - enabling you to log messages with varying levels 19 | of severity. By setting the `LOG_LEVEL` environment variable, you can control 20 | the visibility of the logs. The library is incredibly easy to use, with no 21 | external dependencies. It enhances `console.log` with useful defaults. 22 | 23 | ### Installation 24 | 25 | ```bash 26 | npm install @baselime/lambda-logger 27 | ``` 28 | 29 | ### Usage 30 | 31 | ```javascript 32 | const { logger } = require("@baselime/lambda-logger"); 33 | 34 | logger.info("This is an informational message", { payload: { foo: "bar" } }); 35 | logger.warn("This is a warning message", { payload: { foo: "bar" } }); 36 | logger.debug("This is a debug message", { payload: { foo: "bar" } }); 37 | logger.error("This is an error message", { payload: { foo: "bar" } }); 38 | ``` 39 | 40 | By default, the library only prints logs with a severity level of info or 41 | higher. However, you can control the logging level by setting the LOG_LEVEL 42 | environment variable to one of the following values: 43 | 44 | - `DEBUG`: All log messages will be printed. 45 | - `INFO` (default): Only messages with a severity level of `info`, `warn`, or 46 | `error` will be printed. 47 | - `WARN`: Only messages with a severity level of `warn` or `error` will be 48 | printed. 49 | - `ERROR`: Only messages with a severity level of `error` will be printed. 50 | 51 | Additionally, you can use the `wrap` method to instrument your AWS Lambda 52 | function and gain visibility of its trigger event and response, which can be 53 | helpful when debugging. 54 | 55 | ### Example 56 | 57 | ```javascript 58 | const { wrap, logger } = require("@baselime/lambda-logger"); 59 | 60 | exports.handler = wrap(async (event, context) => { 61 | logger.info("Lambda function started"); 62 | try { 63 | const result = await someAsyncFunction(); 64 | logger.debug("Result", result); 65 | return result; 66 | } catch (error) { 67 | logger.error("Error", error); 68 | throw error; 69 | } 70 | }); 71 | ``` 72 | 73 | ### Middy 74 | 75 | We also support [Middy](https://middy.js.org) The lambda middleware framework. 76 | 77 | ```javascript 78 | import { Baselime, logger } from "@baselime/lambda-logger"; 79 | import middy from "@middy/core"; 80 | 81 | exports.handler = middy() 82 | .use(Baselime()) 83 | .handler(function (e, context) { 84 | const requests = e.Records.map((el) => 85 | Buffer.from(el.kinesis.data, "base64").toString("utf-8") 86 | ); 87 | logger.info("The events to stream", requests); 88 | }); 89 | ``` 90 | 91 | ### Contributing 92 | 93 | If you would like to contribute to the development of this library, please 94 | submit a pull request on GitHub. 95 | 96 | ### License 97 | 98 | This library is licensed under the MIT License. See the [LICENSE](LICENSE) file 99 | for details. 100 | 101 | 102 | 103 | [docs]: https://baselime.io/docs/ 104 | [docs_badge]: https://img.shields.io/badge/docs-reference-blue.svg?style=flat-square 105 | [license]: https://opensource.org/licenses/MIT 106 | [license_badge]: https://img.shields.io/github/license/baselime/lambda-logger.svg?color=blue&style=flat-square&ghcache=unused 107 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {(...any) => any} func 4 | * @returns 5 | */ 6 | export function wrap(func: (...any: any[]) => any): (event: any, context: any, callback: any) => Promise; 7 | export namespace logger { 8 | export { info }; 9 | export { debug }; 10 | export { warn }; 11 | export { error }; 12 | } 13 | declare function MiddyMiddleware(): { 14 | before: ({ event }: { 15 | event: any; 16 | }) => void; 17 | after: ({ response }: { 18 | response: any; 19 | }) => void; 20 | }; 21 | /** 22 | * 23 | * @param {string} message 24 | * @param {Record=} data 25 | */ 26 | declare function info(message: string, data?: Record | undefined): void; 27 | /** 28 | * 29 | * @param {string} message 30 | * @param {Record=} data 31 | */ 32 | declare function debug(message: string, data?: Record | undefined): void; 33 | /** 34 | * @param {string} message 35 | * @param {Record| Error=} dataOrError 36 | * @param {Error=} error 37 | * @returns 38 | */ 39 | declare function warn(message: string, dataOrError?: (Record | Error) | undefined, error?: Error | undefined): void; 40 | /** 41 | * @param {string} message 42 | * @param {Record| Error=} dataOrError 43 | * @param {Error=} error 44 | * @returns 45 | */ 46 | declare function error(message: string, dataOrError?: (Record | Error) | undefined, error?: Error | undefined): void; 47 | export { MiddyMiddleware as Baselime }; 48 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /index.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAkGA;;;;GAIG;AACH,8CAHuB,GAAG,6DAmBzB;;;;;;;AAED;;;;;;;EAaC;AAzFD;;;;GAIG;AACH,+BAHW,MAAM,SACN,OAAO,MAAM,EAAE,GAAG,CAAC,oBAI7B;AAED;;;;GAIG;AACH,gCAHW,MAAM,SACN,OAAO,MAAM,EAAE,GAAG,CAAC,oBAI7B;AAED;;;;;GAKG;AACH,+BALW,MAAM,iBACN,OAAO,MAAM,EAAE,GAAG,CAAC,GAAE,KAAK,uBAC1B,KAAK,oBASf;AAED;;;;;GAKG;AACH,gCALW,MAAM,iBACN,OAAO,MAAM,EAAE,GAAG,CAAC,GAAE,KAAK,uBAC1B,KAAK,oBASf"} -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const LOG_LEVEL = process.env.LOG_LEVEL || "INFO"; 2 | 3 | /** 4 | * 5 | * @param {string} level 6 | * @returns 7 | */ 8 | function isLogged(level) { 9 | if (level === "baselime") { 10 | return true; 11 | } 12 | const levels = ["DEBUG", "INFO", "WARN", "ERROR"]; 13 | 14 | return levels.indexOf(level.toUpperCase()) >= levels.indexOf(LOG_LEVEL); 15 | } 16 | 17 | /** 18 | * 19 | * @param {*} payload 20 | * 21 | */ 22 | function checkPayloadSizeSafe(payload) { 23 | try { 24 | const maxCloudWatchLogSize = 200 * 1024; 25 | const payloadString = JSON.stringify(payload); 26 | return payloadString > maxCloudWatchLogSize ? false : true; 27 | } catch(e) { 28 | return false 29 | } 30 | } 31 | /** 32 | * 33 | * @param {Record=} data 34 | * @param {Error=} err 35 | * @returns 36 | */ 37 | function getErrorData(data, err) { 38 | if (!err) { 39 | return data; 40 | } 41 | 42 | return { 43 | ...(data || {}), 44 | error: { 45 | name: err.name, 46 | message: err.message, 47 | stack: err.stack, 48 | }, 49 | }; 50 | } 51 | 52 | function log(level, message, data) { 53 | if (!isLogged(level)) return; 54 | const logMsg = { 55 | message, 56 | data, 57 | level 58 | }; 59 | 60 | try { 61 | console[level](JSON.stringify(logMsg)); 62 | } catch(err) { 63 | if(err.message.includes("is not a function")) { 64 | console.error(`level ${level} is not a function`); 65 | } 66 | console.error(err); 67 | } 68 | 69 | } 70 | 71 | /** 72 | * 73 | * @param {string} message 74 | * @param {Record=} data 75 | */ 76 | function info(message, data) { 77 | log("info", message, data); 78 | } 79 | 80 | /** 81 | * 82 | * @param {string} message 83 | * @param {Record=} data 84 | */ 85 | function debug(message, data) { 86 | log("debug", message, data); 87 | } 88 | 89 | /** 90 | * @param {string} message 91 | * @param {Record| Error=} dataOrError 92 | * @param {Error=} error 93 | * @returns 94 | */ 95 | function warn(message, dataOrError, error) { 96 | const data = 97 | !error && dataOrError instanceof Error 98 | ? getErrorData({}, dataOrError) 99 | : getErrorData(dataOrError, error); 100 | log("warn", message, data); 101 | } 102 | 103 | /** 104 | * @param {string} message 105 | * @param {Record| Error=} dataOrError 106 | * @param {Error=} error 107 | * @returns 108 | */ 109 | function error(message, dataOrError, error) { 110 | const data = 111 | !error && dataOrError instanceof Error 112 | ? getErrorData({}, dataOrError) 113 | : getErrorData(dataOrError, error); 114 | log("error", message, data); 115 | } 116 | 117 | const logger = { 118 | info, 119 | debug, 120 | warn, 121 | error, 122 | }; 123 | 124 | /** 125 | * @template T 126 | * @param {T} event 127 | * @returns {T} 128 | */ 129 | function decodeEventBody(event) { 130 | if (event.isBase64Encoded) { 131 | return {...event, body: Buffer.from(event.body, 'base64').toString()} 132 | } 133 | return event; 134 | } 135 | 136 | /** 137 | * @template T 138 | * @param {T extends (...any) => any} func 139 | * @returns {T} 140 | */ 141 | function wrap(func) { 142 | const instrumentedLambda = async (event, context, callback) => { 143 | try { 144 | 145 | log("info", "baselime:trigger", { 146 | ...(checkPayloadSizeSafe(event) ? { event: decodeEventBody(event) } : { error: 'Event exceeds 256kb'}), 147 | }); 148 | const response = await func(event, context, callback); 149 | log("info", "baselime:response", { 150 | ...(checkPayloadSizeSafe(response) ? { response } : { error: 'Response exceeds 256kb'}), 151 | }); 152 | return response; 153 | } catch (err) { 154 | log("info", "baselime:error", getErrorData({}, err)); 155 | throw err; 156 | } 157 | }; 158 | return instrumentedLambda; 159 | } 160 | 161 | 162 | function MiddyMiddleware() { 163 | return { 164 | before: ({ event }) => { 165 | log("info", "baselime:trigger", { 166 | event: decodeEventBody(event), 167 | }); 168 | }, 169 | after: ({ response }) => { 170 | log("info", "baselime:response", { 171 | response, 172 | }); 173 | }, 174 | }; 175 | } 176 | 177 | module.exports = { 178 | wrap, 179 | logger, 180 | Baselime: MiddyMiddleware, 181 | }; 182 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@baselime/lambda-logger", 3 | "version": "0.0.1", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "@baselime/lambda-logger", 9 | "version": "0.0.1", 10 | "license": "MIT", 11 | "devDependencies": { 12 | "@types/aws-lambda": "^8.10.114", 13 | "@types/node": "^18.15.11" 14 | } 15 | }, 16 | "node_modules/@types/aws-lambda": { 17 | "version": "8.10.114", 18 | "resolved": "https://registry.npmjs.org/@types/aws-lambda/-/aws-lambda-8.10.114.tgz", 19 | "integrity": "sha512-M8WpEGfC9iQ6V2Ccq6nGIXoQgeVc6z0Ngk8yCOL5V/TYIxshvb0MWQYLFFTZDesL0zmsoBc4OBjG9DB/4rei6w==", 20 | "dev": true 21 | }, 22 | "node_modules/@types/node": { 23 | "version": "18.15.11", 24 | "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", 25 | "integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==", 26 | "dev": true 27 | } 28 | }, 29 | "dependencies": { 30 | "@types/aws-lambda": { 31 | "version": "8.10.114", 32 | "resolved": "https://registry.npmjs.org/@types/aws-lambda/-/aws-lambda-8.10.114.tgz", 33 | "integrity": "sha512-M8WpEGfC9iQ6V2Ccq6nGIXoQgeVc6z0Ngk8yCOL5V/TYIxshvb0MWQYLFFTZDesL0zmsoBc4OBjG9DB/4rei6w==", 34 | "dev": true 35 | }, 36 | "@types/node": { 37 | "version": "18.15.11", 38 | "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", 39 | "integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==", 40 | "dev": true 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@baselime/lambda-logger", 3 | "version": "0.2.2", 4 | "description": "An opinionated logger for AWS Lambda", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/baselime/lambda-logger.git" 12 | }, 13 | "author": "", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/baselime/lambda-logger/issues" 17 | }, 18 | "homepage": "https://github.com/baselime/lambda-logger#readme", 19 | "devDependencies": { 20 | "@types/aws-lambda": "^8.10.114", 21 | "@types/node": "^18.15.11" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // Change this to match your project 3 | "include": ["./index.js"], 4 | "compilerOptions": { 5 | // Generate d.ts files 6 | "allowJs": true, 7 | "declaration": true, 8 | // This compiler run should 9 | // only output d.ts files 10 | "emitDeclarationOnly": true, 11 | // Types should go into this directory. 12 | // Removing this would place the .d.ts files 13 | // next to the .js files 14 | // go to js file when using IDE functions like 15 | // "Go to Definition" in VSCode 16 | "declarationMap": true 17 | } 18 | } --------------------------------------------------------------------------------