├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── jest.config.js ├── package.json ├── src ├── logger.ts ├── main.ts ├── strings.ts ├── system.ts ├── types.ts └── wrapper.ts ├── test ├── logger.spec.ts └── wrapper.spec.ts ├── tsconfig.json ├── tsconfig.test.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.test.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint'], 8 | extends: [ 9 | 'eslint:recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | 'no-console': 'error', 25 | }, 26 | } 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | .history/ 39 | xunit.xml 40 | dist/ 41 | lib/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "semi": false 4 | } 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log / Release Notes 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | ## [4.0.0] - 2021-02-01 8 | ### Changed 9 | - **BREAKING CHANGE** API for Formatters 10 | - Converted entire project to typescript 11 | ### Removed 12 | - Support for Node < 12.10 13 | 14 | ## [3.3.0] - 2021-02-01 15 | ### Added 16 | - New Log Level `SILENT` 17 | 18 | ## [3.2.1] - 2019-12-23 19 | ### Fixed 20 | - proxyquire listed as dependency instead of devDependency 21 | 22 | ## [3.2.0] - 2019-12-23 23 | ### Added 24 | - export `wrapper` function 25 | 26 | ## [3.1.4] - 2019-10-29 27 | ### Fixed 28 | - Log message severity double prepending on Node 10 29 | 30 | ## [3.1.3] - 2019-10-29 31 | ### Fixed 32 | - Debug log message causing encoding error 33 | 34 | ## [3.1.2] - 2019-10-29 35 | ### Fixed 36 | - Node 10.x runtime error 37 | 38 | ## [3.1.1] - 2019-06-11 39 | ### Fixed 40 | - `testMode` detection 41 | 42 | ## [3.1.0] - 2019-01-28 43 | ### Added 44 | - `testMode` constructor option to override ENV checks 45 | - Light-weight formatter for test mode 46 | 47 | ## [3.0.1] - 2019-01-28 48 | ### Fixed 49 | - Regex redactors not redacting all instances 50 | 51 | ## [3.0.0] - 2019-01-02 52 | ### Changed 53 | - Total re-write of the loggers internals and API 54 | 55 | ## [2.3.0] - 2018-04-25 56 | ### Added 57 | - Support async handlers (return promise instead of using callback) 58 | 59 | ## [2.2.1] - 2018-03-02 60 | ### Fixed 61 | - Possible infinite recursion when running outside of a lambda (again) 62 | 63 | ## [2.2.0] - 2018-02-08 64 | ### Added 65 | - `delimiter` option 66 | ### Fixed 67 | - Possible infinite recursion when running outside of a lambda 68 | 69 | ## [2.1.1] - 2017-11-16 70 | ### Fixed 71 | - Failure due to inability to serialize result 72 | 73 | ## [2.1.0] - 2017-06-11 74 | ### Added 75 | - Initial release 76 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | There are a few guidelines that we need contributors to follow so that we are able to process requests as efficiently as possible. If you have any questions or concerns please feel free to contact us at [opensource@nike.com](mailto:opensource@nike.com). 4 | 5 | ## Getting Started 6 | 7 | * Review our [Code of Conduct](https://github.com/Nike-Inc/nike-inc.github.io/blob/master/CONDUCT.md) 8 | * Submit the [Individual Contributor License Agreement](https://www.clahub.com/agreements/Nike-Inc/fastbreak) 9 | * Make sure you have a [GitHub account](https://github.com/signup/free) 10 | * Submit a ticket for your issue, assuming one does not already exist. 11 | * Clearly describe the issue including steps to reproduce when it is a bug. 12 | * Make sure you fill in the earliest version that you know has the issue. 13 | * Fork the repository on GitHub 14 | 15 | ## Making Changes 16 | 17 | * Create a topic branch off of `master` before you start your work. 18 | * Please avoid working directly on the `master` branch. 19 | * Make commits of logical units. 20 | * You may be asked to squash unnecessary commits down to logical units. 21 | * Check for unnecessary whitespace with `git diff --check` before committing. 22 | * Write meaningful, descriptive commit messages. 23 | * Please follow existing code conventions when working on a file. 24 | 25 | ## Submitting Changes 26 | 27 | * Push your changes to a topic branch in your fork of the repository. 28 | * Submit a pull request to the repository in the Nike-Inc organization. 29 | * After feedback has been given we expect responses within two weeks. After two weeks we may close the pull request if it isn't showing any activity. 30 | * Bug fixes or features that lack appropriate tests may not be considered for merge. 31 | * Changes that lower test coverage may not be considered for merge. 32 | 33 | # Additional Resources 34 | 35 | * [General GitHub documentation](https://help.github.com/) 36 | * [GitHub pull request documentation](https://help.github.com/send-pull-requests/) 37 | * [Nike's Code of Conduct](https://github.com/Nike-Inc/nike-inc.github.io/blob/master/CONDUCT.md) 38 | * [Nike's Individual Contributor License Agreement](https://www.clahub.com/agreements/Nike-Inc/fastbreak) 39 | * [Nike OSS](https://nike-inc.github.io/) 40 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Nike, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lambda-logger-node 2 | 3 | A middleware logger that implements the MDC logging pattern for use in AWS NodeJS Lambdas. It provides 4 log levels (DEBUG, INFO, WARN, ERROR), custom message attributes, and allows the creation of sub-loggers. 4 | 5 | It is designed to make log messages easily readable by humans from Cloudwatch, as well as easily parsed by machines for ingestion into downstream systems like the ELK stack. When a log call is made the log level and message are placed first, followed by a JSON-stringified object that contains the message and custom attributes. 6 | 7 | Since v3 lambda-logger-node only supports wrapping async function handlers. 8 | 9 | ## Quick Start 10 | 11 | ```javascript 12 | // lambda.js 13 | const { Logger } = require('lambda-logger-node') 14 | let logger = Logger() 15 | logger.setKey('custom', 'value') 16 | 17 | exports.handler = logger.handler(handler) 18 | async function handler (event, context) { 19 | logger.info('test message') // -> 20 | /* 21 | INFO test message | ___$LAMBDA-LOG-TAG$___{ 22 | "traceId":"8sd3g32-42fg-43th45h-vsafd", 23 | "date":"2018-12-17T23:37:24Z", 24 | "appName":"your-app-name", 25 | "apigTraceId":"897635-3534-33435-435", 26 | "traceIndex":0, 27 | "custom":"value", 28 | "message":"test message", 29 | "severity":"INFO", 30 | "contextPath":""}___$LAMBDA-LOG-TAG$___ <-- one line when loged, whitespace for docs 31 | */ 32 | } 33 | ``` 34 | 35 | # Installation 36 | 37 | ``` 38 | npm install lambda-logger-node 39 | ``` 40 | 41 | # Usage 42 | 43 | Simple Lambda handler 44 | 45 | ```javascript 46 | const { Logger } = require('lambda-logger-node') 47 | const logger = Logger() 48 | 49 | exports.handler = logger.handler(handler) 50 | 51 | async function handler (event, context) { 52 | // your lambda handler 53 | } 54 | 55 | ``` 56 | 57 | Or, with more middleware 58 | 59 | ```javascript 60 | const { Logger } = require('lambda-logger-node') 61 | const logger = Logger() 62 | var moreMiddleware = require('more-middleware') 63 | 64 | exports.handler = logger.handler(moreMiddleware(handler)) 65 | 66 | async function handler (event, context) { 67 | // your lambda handler 68 | } 69 | ``` 70 | 71 | ## Recommended setup 72 | 73 | To simplify usage of the logger throughout your application configure a logger in its own module. 74 | 75 | ```javascript 76 | // logger.js 77 | const config = require('./config') 78 | const { Logger } = require('lambda-logger-node') 79 | const logger = Logger({ 80 | minimumLogLevel = config.isProduction ? 'INFO' : null 81 | }) 82 | 83 | module.exports = logger 84 | 85 | // lambda.js 86 | const logger = require('./logger') 87 | exports.handler = logger.handler(handler) 88 | async function handler (event, context) { 89 | // your lambda handler 90 | } 91 | 92 | // api.js 93 | const logger = require('./logger') 94 | module.exports { someFunc } 95 | 96 | function someFunc() { 97 | // app code 98 | logger.info('custom log') 99 | } 100 | ``` 101 | 102 | In addition to this method allowing global use of your lambda, the logger is attached to the handler's `context` argument as `context.logger`. When the lambda handler is executed all of the request-specific values (like the *traceId*) are updated, even when the module is declared and `required` outside the handler like the one above. 103 | 104 | # Logger API 105 | 106 | The Logger module exports a constructor on `Logger` that takes the following options 107 | 108 | ```javascript 109 | function Logger ({ 110 | minimumLogLevel = null, 111 | useGlobalErrorHandler = true, 112 | redactors = [], 113 | useBearerRedactor = true, 114 | formatter = JsonFormatter 115 | } = {}) 116 | ``` 117 | 118 | * `string: minimumLogLevel`: one of DEBUG | INFO | WARN | ERROR. Supress messages that are below this level in severity. 119 | * `bool:useGlobalErrorHandler`: default: `true`. Attach process-level handlers for uncaught exceptions and unhandled rejections to log messages with the logger. Attempting to construct two loggers with this setting will result in an error, 120 | * `[string|RegExp|func]:redactors`: an array of redactors to process all log messages with. A `string` will be removed verbatim, a `RegExp` will be removed if it matches. If a function is given it is passed the log message as a string, and *MUST* return a string (whether it replaced anything or not). 121 | * `bool: useBearerRedactor`: default: `true`, add a bearer token redactor to the list of redactors. 122 | * `bool: testMode`: Override environment checks and force "testMode" to be `true` or `false`. Leave `undefined` to allow ENV to define test mode. 123 | * `func: formatter`: format messages before they are written out. The default formatter is used if this option is left off. This is an advanced customization point, and a deep understanding of the logger will be necessary to implement a custom formatter (there are no docs other than source code right now). 124 | 125 | The Logger constructor returns a logger instance with the following API 126 | 127 | ``` 128 | { 129 | handler, 130 | setMinimumLogLevel, 131 | events, 132 | setKey, 133 | createSubLogger, 134 | info, 135 | warn, 136 | error, 137 | debug 138 | } 139 | ``` 140 | 141 | * `handler`: Takes a handler function as input and returns a wrapped handler function that configures per-request keys such as `traceId`. 142 | * `setMinimumLogLevel`: Takes a log level (DEBUG | INFO | WARN | ERROR) and sets the same `minimumLogLevel` that the constructor took. Useful if this is not known until the handler has executed. 143 | * `events`: an `EventEmitter`. Currently only supports `beforeHandler`. 144 | * `setKey`: add a custom sttribute to all log messages. First argument is a string name for the attributes. The second argument is a value, or a value-returning function (function will be executed at log-time). 145 | * `debug|info|warn|error`: Create a log for the matching severity. 146 | * `createSubLogger(string: subLoggerName)`: Creates a sub-logger that only has the log methods (`debug|info|warn|error`) and `createSubLogger`. Useful for providing loggers to sub-components like your Dynamo Client. Its messages are prefixed with the sub-loggers name; if there are multiple levels of sub-loggers each sub-logger is included in the prefix. e.g. for a sub-logger "SubTwo" that is a sub-logger of another sub-logger "SubOne" the message would be `INFO SubOne.SubTwo message`. 147 | 148 | 149 | # Events 150 | 151 | The logger also contains an event emitter that will emit a `beforeHandler` event just before the lambda handler function is called. This receives both the lambda event and context as arguments. For example, you could use this to generate a custom `traceId` key/value pair in your logs: 152 | 153 | ```js 154 | const nanoid = require('nanoid') 155 | 156 | logger.events.on('beforeHandler', (lambdaEvent, context) => { 157 | logger.setKey('traceId', nanoid()) 158 | }) 159 | ``` 160 | 161 | This will use a custom value generated by the `nanoid` library, rather than the default `awsRequestId`. 162 | 163 | # Logger Wrapper 164 | 165 | This module exports a `wrapper` function that returns an API-comptatible logger object regardless of what is passed in (including `undefined`). This useful for creating objects that can be provided a logger with missing methods (maybe you don't want to see `debug`); especially useful for testing classes without providing them a logger _at all_. 166 | 167 | ```js 168 | const { wrapper } = require('lambda-logger-node') 169 | module.exports = constructor 170 | 171 | function constructor (options) { 172 | const logger = wrapper(options.logger) 173 | 174 | logger.error('This will only log if the options.logger already has an error method') 175 | logger.warn('This will only log if the options.logger already has a warn method') 176 | logger.info('This will only log if the options.logger already has an info method') 177 | logger.debug('This will only log if the options.logger already has a debug method') 178 | } 179 | ``` 180 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | watchPlugins: [ 5 | 'jest-watch-typeahead/filename', 6 | 'jest-watch-typeahead/testname', 7 | ], 8 | globals: { 9 | 'ts-jest': { 10 | tsconfig: 'tsconfig.test.json', 11 | }, 12 | }, 13 | } 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lambda-logger-node", 3 | "version": "4.0.0-7", 4 | "description": "A logger middleware for AWS Lambda functions", 5 | "main": "lib/main.js", 6 | "typings": "lib/types/main.d.ts", 7 | "author": "Tim Kye", 8 | "license": "Apache-2.0", 9 | "scripts": { 10 | "test": "run-s check test:unit", 11 | "test:unit": "jest", 12 | "test:watch": "jest --watch", 13 | "build": "run-s check build:tsc", 14 | "build:tsc": "del lib/ && tsc ", 15 | "style": "prettier --write \"{src,test}/**/*.ts\"", 16 | "size": "run-s build size:check", 17 | "size:check": "size-limit", 18 | "lint": "eslint \"{src,test}/**/*.ts\"", 19 | "check": "npm run style && npm run lint", 20 | "release": "npm run build && np" 21 | }, 22 | "files": [ 23 | "lib" 24 | ], 25 | "engines": { 26 | "node": ">=12.10" 27 | }, 28 | "repository": "ssh:/git@github.com:Nike-Inc/lambda-logger-node.git", 29 | "keywords": [ 30 | "lambda", 31 | "logger" 32 | ], 33 | "dependencies": { 34 | "fast-safe-stringify": "^2.0.6" 35 | }, 36 | "devDependencies": { 37 | "@size-limit/preset-small-lib": "^4.7.0", 38 | "@types/jest": "^27.4.1", 39 | "@types/node": "^17.0.21", 40 | "@typescript-eslint/eslint-plugin": "^5.13.0", 41 | "@typescript-eslint/parser": "^5.13.0", 42 | "del-cli": "^4.0.1", 43 | "eslint": "^8.10.0", 44 | "eslint-config-prettier": "^8.5.0", 45 | "eslint-plugin-prettier": "^4.0.0", 46 | "jest": "^27.5.1", 47 | "jest-watch-typeahead": "^1.0.0", 48 | "np": "^7.0.0", 49 | "npm-run-all": "^4.1.5", 50 | "prettier": "^2.5.1", 51 | "size-limit": "^4.7.0", 52 | "ts-jest": "^27.1.3", 53 | "typescript": "^4.6.2" 54 | }, 55 | "size-limit": [ 56 | { 57 | "webpack": false, 58 | "path": "lib/*.js", 59 | "limit": "6kb" 60 | } 61 | ] 62 | } 63 | -------------------------------------------------------------------------------- /src/logger.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from 'events' 2 | import jsonify from 'fast-safe-stringify' 3 | import { stringRedactor, regexRedactor, redact, Redactor } from './strings' 4 | import * as system from './system' 5 | 6 | import { logLevels, severities } from './types' 7 | import type { LogFn, ILogger, LogLevel, Severity } from './types' 8 | 9 | /* 10 | Properties of an ideal logger 11 | accepts variadic arguments 12 | nicely formats messages 13 | severity suppression 14 | redaction 15 | sub contexts 16 | allows custom formatting of objects 17 | */ 18 | 19 | export const LOG_DELIMITER = '___$LAMBDA-LOG-TAG$___' 20 | const reservedKeys = ['message', 'severity'] 21 | 22 | // I don't want to include the enormous AWS types to 23 | // correctly type the handler function 24 | // eslint-disable-next-line @typescript-eslint/ban-types 25 | type Handler = Function 26 | 27 | export type Formatter = ( 28 | context: FormatContext, 29 | severity: typeof severities[number], 30 | ...args: unknown[] 31 | ) => string 32 | export type Loggable = string | boolean | number 33 | 34 | export interface LoggerWithSub extends ILogger { 35 | createSubLogger: (name: string) => LoggerWithSub 36 | } 37 | export interface LambdaLogger extends LoggerWithSub { 38 | handler: Handler 39 | setMinimumLogLevel: (level: LogLevel) => void 40 | events: EventEmitter 41 | setKey: (key: string, val: Loggable | (() => Loggable)) => void 42 | } 43 | 44 | export interface FormatContext { 45 | keys: Record 46 | contextPath: string[] 47 | } 48 | 49 | interface LogContext { 50 | minimumLogLevel?: LogLevel 51 | redact: Redactor 52 | redactors: Redactor[] 53 | formatter: Formatter 54 | events: EventEmitter 55 | contextPath: string[] 56 | testMode?: boolean 57 | keys: Map Loggable)> 58 | logger: LambdaLogger 59 | globalErrorHandler?: (error: any, promise: any) => void 60 | } 61 | 62 | // module.exports = { 63 | // logLevels, 64 | // LOG_DELIMITER, 65 | // Logger, 66 | // wrapper 67 | // } 68 | 69 | export interface LoggerProps { 70 | /** Hide log entries of lower severity */ 71 | minimumLogLevel?: LogLevel 72 | /** Function that formats the log message; receives the logContext, severity, and the N-arity log arguments */ 73 | formatter?: Formatter 74 | /** add a Bearer token redactor. Default true */ 75 | useBearerRedactor?: boolean 76 | /** setup global handlers for uncaughtException and unhandledRejection. Only one logger per-lambda can use this option. */ 77 | useGlobalErrorHandler?: boolean 78 | forceGlobalErrorHandler?: boolean 79 | redactors?: (Redactor | string | RegExp)[] 80 | testMode?: boolean 81 | } 82 | 83 | export function Logger({ 84 | minimumLogLevel, 85 | formatter, 86 | useBearerRedactor = true, 87 | useGlobalErrorHandler = true, 88 | forceGlobalErrorHandler = false, 89 | redactors = [], 90 | testMode = undefined, 91 | }: LoggerProps = {}): LambdaLogger { 92 | // This wacky omit it just to make typescript happy regarding the props 93 | // that are initialized later in this function 94 | const initContext: Partial = { 95 | minimumLogLevel, 96 | formatter: 97 | formatter ?? isInTestMode(testMode) ? LineFormatter : JsonFormatter, 98 | events: new EventEmitter(), 99 | contextPath: [], 100 | testMode, 101 | keys: new Map(), 102 | } 103 | if (useBearerRedactor) { 104 | redactors.push(bearerRedactor(initContext as LogContext)) 105 | } 106 | if (useGlobalErrorHandler) { 107 | registerErrorHandlers(initContext as LogContext, forceGlobalErrorHandler) 108 | } 109 | initContext.redact = createRedact(initContext as LogContext, redactors) 110 | 111 | // 112 | // All Omit props should be filled by this point 113 | // 114 | const context: LogContext = initContext as LogContext 115 | 116 | context.logger = { 117 | handler: wrapHandler(context), 118 | setMinimumLogLevel: wrapSetMinimumLogLevel(context), 119 | events: context.events, 120 | setKey: wrapSetKey(context), 121 | ...createLogger(context), 122 | } 123 | 124 | return context.logger 125 | } 126 | 127 | function createLogger(logContext: LogContext): LoggerWithSub { 128 | const severityLog = wrapLog(logContext) 129 | return { 130 | createSubLogger: wrapSubLogger(logContext), 131 | info: severityLog('info'), 132 | warn: severityLog('warn'), 133 | error: severityLog('error'), 134 | debug: severityLog('debug'), 135 | } 136 | } 137 | 138 | function wrapSubLogger( 139 | logContext: LogContext 140 | ): (name: string) => LoggerWithSub { 141 | return (name: string) => 142 | createLogger({ 143 | ...logContext, 144 | // Reference parent's minimumLogLevel so that it cascades down 145 | get minimumLogLevel() { 146 | return logContext.minimumLogLevel 147 | }, 148 | contextPath: [...logContext.contextPath, name], 149 | // TODO: Figure out why you were doing this 150 | // logger: undefined 151 | }) 152 | } 153 | 154 | function wrapHandler(logContext: LogContext) { 155 | return (handler: Handler) => 156 | async (lambdaEvent: unknown, lambdaContext: unknown) => { 157 | // Create initial values from context 158 | setMdcKeys(logContext, lambdaEvent, lambdaContext) 159 | 160 | // Attach logger to context 161 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 162 | // @ts-ignore 163 | lambdaContext.logger = logContext.logger 164 | 165 | if (logContext.events) 166 | logContext.events.emit('beforeHandler', lambdaEvent, lambdaContext) 167 | 168 | const result = handler(lambdaEvent, lambdaContext) 169 | if (!isPromise(result)) { 170 | // log the error first 171 | throw new Error( 172 | 'Logger wrapped a handler function that did not return a promise. Lambda logger only supports async handlers.' 173 | ) 174 | } 175 | return result 176 | } 177 | } 178 | 179 | function wrapSetKey( 180 | logContext: LogContext 181 | ): (key: string, val: Loggable | (() => Loggable)) => void { 182 | return (key: string, value: Loggable | (() => Loggable)) => { 183 | if (reservedKeys.includes(key)) { 184 | throw new Error(`"${key}" is a reserved logger key.`) 185 | } 186 | logContext.keys.set(key, value) 187 | } 188 | } 189 | 190 | function setMdcKeys( 191 | logContext: LogContext, 192 | lambdaEvent: any, 193 | lambdaContext: any 194 | ) { 195 | let traceIndex = 0 196 | 197 | logContext.logger.setKey('traceId', lambdaContext.awsRequestId) 198 | logContext.logger.setKey('date', getFormattedDate) 199 | logContext.logger.setKey('appName', lambdaContext.functionName) 200 | logContext.logger.setKey('version', lambdaContext.functionVersion) 201 | logContext.logger.setKey( 202 | 'apigTraceId', 203 | (lambdaEvent && 204 | lambdaEvent.requestContext && 205 | lambdaEvent.requestContext.requestId) || 206 | (lambdaContext && 207 | lambdaContext.requestContext && 208 | lambdaContext.requestContext.requestId) 209 | ) 210 | logContext.logger.setKey('traceIndex', () => traceIndex++) 211 | } 212 | 213 | function wrapLog(logContext: LogContext): (sev: Severity) => LogFn { 214 | return (severity: Severity) => 215 | (...args: unknown[]) => 216 | writeLog(logContext, severity, ...args) 217 | } 218 | 219 | function writeLog( 220 | logContext: LogContext, 221 | severity: Severity, 222 | ...args: unknown[] 223 | ) { 224 | if (!canLogSeverity(logContext, severity)) return 225 | const logMessage = getLogMessage(logContext, severity, ...args) 226 | 227 | switch (severity) { 228 | case 'warn': 229 | system.console.warn(logMessage) 230 | return 231 | case 'error': 232 | system.console.error(logMessage) 233 | return 234 | case 'debug': 235 | system.console.debug(logMessage) 236 | return 237 | case 'info': 238 | default: 239 | system.console.log(logMessage) 240 | } 241 | } 242 | 243 | function getLogMessage( 244 | logContext: LogContext, 245 | severity: Severity, 246 | ...args: unknown[] 247 | ) { 248 | const keys = Object.fromEntries( 249 | Array.from(logContext.keys.entries()).map(([key, value]) => [ 250 | key, 251 | typeof value === 'function' ? value() : value, 252 | ]) 253 | ) 254 | 255 | return logContext.redact( 256 | logContext.formatter( 257 | { keys, contextPath: logContext.contextPath }, 258 | severity, 259 | ...args 260 | ) 261 | ) 262 | } 263 | 264 | function canLogSeverity(logContext: LogContext, severity: Severity) { 265 | if (!severities.includes(severity)) 266 | throw new Error('Unable to log, illegal severity: ' + severity) 267 | return !( 268 | logContext.minimumLogLevel && 269 | severity && 270 | logLevels.indexOf(severity.toUpperCase()) < 271 | logLevels.indexOf(logContext.minimumLogLevel) 272 | ) 273 | } 274 | 275 | function wrapSetMinimumLogLevel( 276 | logContext: LogContext 277 | ): (level: LogLevel) => void { 278 | return (level: LogLevel) => { 279 | if (logLevels.indexOf(level) === -1) { 280 | throw new Error('Illegal log level value: ' + level) 281 | } 282 | logContext.minimumLogLevel = level 283 | } 284 | } 285 | 286 | function formatMessageItem(message: unknown) { 287 | if (typeof message === 'string') return message 288 | return jsonify(message, undefined, 2) 289 | } 290 | 291 | export function JsonFormatter( 292 | context: FormatContext, 293 | severity: Severity, 294 | ...args: unknown[] 295 | ) { 296 | const log: Record = { 297 | ...context.keys, 298 | } 299 | log.message = 300 | args.length === 1 301 | ? formatMessageItem(args[0]) 302 | : args.map(formatMessageItem).join(' ') 303 | log.severity = severity.toUpperCase() 304 | const subLogPath = getLogPath(context.contextPath) 305 | log.contextPath = subLogPath || undefined 306 | // put the un-annotated message first to make cloudwatch viewing easier 307 | // include the MDC annotaed message after with log delimiter to enable parsing 308 | return `${subLogPath ? ` ${subLogPath} ` : ''}${ 309 | log.message 310 | } |\n ${withDelimiter(jsonify(log))}` 311 | } 312 | 313 | export function LineFormatter( 314 | context: FormatContext, 315 | severity: Severity, 316 | ...args: unknown[] 317 | ) { 318 | const subLogPath = getLogPath(context.contextPath) 319 | const message = 320 | args.length === 1 321 | ? formatMessageItem(args[0]) 322 | : args.map(formatMessageItem).join(' ') 323 | return `${subLogPath ? ` ${subLogPath} ` : ''}${message}` 324 | } 325 | 326 | function withDelimiter(message: string) { 327 | return LOG_DELIMITER + message + LOG_DELIMITER 328 | } 329 | 330 | function getLogPath(paths: string[]): string { 331 | return paths.join('.') 332 | } 333 | 334 | // Redaction 335 | // 336 | 337 | function createRedact( 338 | logContext: LogContext, 339 | redactors: (Redactor | string | RegExp)[] 340 | ): Redactor { 341 | logContext.redactors = redactors.map((redactor) => { 342 | if (typeof redactor === 'string') return stringRedactor(redactor) 343 | else if (redactor instanceof RegExp) return regexRedactor(redactor) 344 | else if (typeof redactor === 'function') return redactor 345 | 346 | throw new Error(`Redactor type not supported: ${redactor}`) 347 | }) 348 | return (value: string) => 349 | logContext.redactors.reduce((val, redactor) => redactor(val), value) 350 | } 351 | 352 | function bearerRedactor(logContext: LogContext): Redactor { 353 | const tokens: string[] = [] 354 | const bearerRegex = /Bearer ([A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*)/ // eslint-disable-line no-useless-escape 355 | // Only keep the token for the current handler invocation 356 | if (logContext.events) { 357 | logContext.events.on('beforeHandler', () => { 358 | clearArray(tokens) 359 | }) 360 | } 361 | return (val: string) => { 362 | // Don't handle empty or non-string values 363 | if (!val || typeof val !== 'string') return val 364 | // Redact early, or... 365 | const token = tokens.find((f) => val.includes(f)) 366 | if (token) return redact(val, token) 367 | // match the token 368 | const match = val.match(bearerRegex) 369 | if (!match) return val 370 | const bareToken = match[1] 371 | // When not using the handler wrapper, "tokens" grows unbounded 372 | // Don't keep more than 5 tokens 373 | // Since each token is the full and bare entry, length = 10 374 | if (tokens.length > 10) { 375 | // Remove the last match-pair 376 | tokens.splice(0, 2) 377 | } 378 | // Store the match pair 379 | tokens.push(val, bareToken) 380 | return redact(val, match[0]) 381 | } 382 | } 383 | 384 | // Error Handling 385 | // 386 | 387 | function registerErrorHandlers(logContext: LogContext, force: boolean) { 388 | if (!force && isInTestMode(logContext.testMode)) { 389 | return 390 | } 391 | clearLambdaExceptionHandlers() 392 | logContext.globalErrorHandler = (err, promise) => { 393 | if (promise) { 394 | logContext.logger.error( 395 | 'unhandled rejection (this should never happen!)', 396 | err.stack 397 | ) 398 | } else { 399 | logContext.logger.error( 400 | 'uncaught exception (this should never happen!)', 401 | err.stack 402 | ) 403 | } 404 | // eslint-disable-next-line no-process-exit 405 | system.process.exit(1) 406 | } 407 | system.process.on('uncaughtException', logContext.globalErrorHandler) 408 | system.process.on('unhandledRejection', logContext.globalErrorHandler) 409 | } 410 | 411 | let hasAlreadyClearedLambdaHandlers = false 412 | function clearLambdaExceptionHandlers() { 413 | if (hasAlreadyClearedLambdaHandlers) { 414 | throw new Error( 415 | 'tried to setup global handlers twice. You cannot construct two Loggers with "useGlobalErrorHandler"' 416 | ) 417 | } 418 | // Taken from: https://gist.github.com/twolfson/855a823cfbd62d4c7405a38105c23fd3 419 | // DEV: AWS Lambda's `uncaughtException` handler logs `err.stack` and exits forcefully 420 | // uncaughtException listeners = [function (err) { console.error(err.stack); system.process.exit(1); }] 421 | // We remove it so we can catch async errors and report them to Rollbar 422 | if (system.process.listeners('uncaughtException').length !== 1) { 423 | throw new Error( 424 | 'Logger Assertion Failed: uncaughtException does not have 1 listener(s)' 425 | ) 426 | } 427 | system.process.removeAllListeners('uncaughtException') 428 | if ( 429 | system.process.listeners('unhandledRejection').length !== 430 | system.UNHANDLED_REJECTION_LISTENERS 431 | ) { 432 | throw new Error( 433 | `Logger Assertion Failed: unhandledRejection does not have ${system.UNHANDLED_REJECTION_LISTENERS} listener(s)` 434 | ) 435 | } 436 | system.process.removeAllListeners('unhandledRejection') 437 | hasAlreadyClearedLambdaHandlers = true 438 | } 439 | 440 | // Utilities 441 | 442 | function isInTestMode(testMode?: boolean) { 443 | // Override with context 444 | if (testMode !== undefined) return testMode 445 | // Check environment 446 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 447 | // @ts-ignore 448 | const isMocha = global.it !== undefined 449 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 450 | // @ts-ignore 451 | const isJest = global.jest !== undefined 452 | const isTape = hasModuleLoaded('tape') 453 | // console.log('has tape loaded', isTape) 454 | const env = 455 | system.process.env.TEST || 456 | system.process.env.test || 457 | system.process.env.ci || 458 | system.process.env.CI 459 | // console.log('load', env, isMocha, isJest, isTape) 460 | return env || isMocha || isJest || isTape 461 | } 462 | 463 | function hasModuleLoaded(moduleName: string) { 464 | try { 465 | return !!require.cache[require.resolve(moduleName)] 466 | } catch (e: any) { 467 | if (/Cannot find module/.test(e.toString())) return false 468 | throw e 469 | } 470 | } 471 | 472 | function pad(n: number): string | number { 473 | return n < 10 ? '0' + n : n 474 | } 475 | 476 | function getFormattedDate(): string { 477 | return formatRfc3339(new Date(Date.now())) 478 | } 479 | 480 | function formatRfc3339(d: Date) { 481 | return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad( 482 | d.getUTCDate() 483 | )}T${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad( 484 | d.getUTCSeconds() 485 | )}Z` 486 | } 487 | 488 | function isPromise(promise: unknown): boolean { 489 | return ( 490 | !!promise && 491 | (promise as Promise).then !== undefined && 492 | typeof (promise as Promise).then === 'function' 493 | ) 494 | } 495 | 496 | function clearArray(arr: unknown[]): void { 497 | arr.length = 0 498 | } 499 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | export { 2 | LOG_DELIMITER, 3 | Logger, 4 | LoggerProps, 5 | Formatter, 6 | Loggable, 7 | LoggerWithSub, 8 | LambdaLogger, 9 | LineFormatter, 10 | JsonFormatter, 11 | } from './logger' 12 | 13 | export { wrapper } from './wrapper' 14 | export { 15 | severities, 16 | logLevels, 17 | LogFn, 18 | ILogger, 19 | LogLevel, 20 | Severity, 21 | } from './types' 22 | -------------------------------------------------------------------------------- /src/strings.ts: -------------------------------------------------------------------------------- 1 | const REDACTION = '--redacted--' 2 | 3 | export type Redactor = (val: string) => string 4 | 5 | export function stringRedactor(find: string): Redactor { 6 | return (val) => replaceAll(val, find, REDACTION) 7 | } 8 | 9 | export function regexRedactor(find: RegExp): Redactor { 10 | // force global replace 11 | const findAll = new RegExp(find.source, 'g') 12 | return (val) => replaceAllRegex(val, findAll, REDACTION) 13 | } 14 | 15 | export function replaceAllRegex( 16 | str: string, 17 | regex: RegExp, 18 | replace: string 19 | ): string { 20 | return str.replace(regex, replace) 21 | } 22 | 23 | export function redact(str: string, find: string): string { 24 | return replaceAll(str, find, REDACTION) 25 | } 26 | 27 | // Taken from https://stackoverflow.com/a/1144788/788260 28 | export function replaceAll(str: string, find: string, replace: string): string { 29 | return str.replace(new RegExp(escapeRegExp(find), 'g'), replace) 30 | } 31 | function escapeRegExp(str: string): string { 32 | return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1') // eslint-disable-line 33 | } 34 | -------------------------------------------------------------------------------- /src/system.ts: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | /* 4 | Mocking these values across Node 8 and Node 10 5 | Is difficult and error-prone 6 | Providing them from here lets us mock them easily 7 | */ 8 | 9 | const p = process 10 | const c = console 11 | export { p as process } 12 | export { c as console } 13 | 14 | // In previous versions this depended on the version of node 15 | // But those versions are no longer supported 16 | export const UNHANDLED_REJECTION_LISTENERS = 1 17 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | // Only include types in here that cannot be safely placed in other files due to circular references 2 | 3 | export const severities = ['debug', 'info', 'warn', 'error'] as const 4 | export const logLevels = [...severities, 'silent'].map((s) => s.toUpperCase()) 5 | 6 | export type LogLevel = Uppercase | 'SILENT' 7 | export type Severity = typeof severities[number] 8 | 9 | export type LogFn = (...args: unknown[]) => ReturnType 10 | export interface ILogger { 11 | debug: LogFn 12 | info: LogFn 13 | error: LogFn 14 | warn: LogFn 15 | minimumLogLevel?: typeof logLevels[number] 16 | } 17 | -------------------------------------------------------------------------------- /src/wrapper.ts: -------------------------------------------------------------------------------- 1 | import { logLevels } from './types' 2 | import type { ILogger, LogFn, Severity } from './types' 3 | 4 | // eslint-disable-next-line @typescript-eslint/no-empty-function 5 | const noop = () => {} 6 | 7 | export function wrapper(baseLogger: any): ILogger { 8 | const logger = baseLogger || {} 9 | if ( 10 | logger.minimumLogLevel !== undefined && 11 | !logLevels.includes(logger.minimumLogLevel) 12 | ) { 13 | throw new Error( 14 | `"minimumLogLevel" must be one of: ${logLevels.join(', ')} or "undefined"` 15 | ) 16 | } 17 | 18 | return { 19 | debug: wrapLogFn(logger, 'debug'), 20 | info: wrapLogFn(logger, 'info'), 21 | warn: wrapLogFn(logger, 'warn'), 22 | error: wrapLogFn(logger, 'error'), 23 | } 24 | } 25 | 26 | function wrapLogFn(logger: Partial, prop: Severity): LogFn { 27 | let func: LogFn 28 | const logFn = logger[prop] 29 | if (logFn && typeof logFn === 'function') { 30 | func = logFn 31 | } else { 32 | func = 33 | logger.minimumLogLevel !== undefined 34 | ? // eslint-disable-next-line no-console 35 | (console[prop] || console.log).bind(console) 36 | : noop 37 | } 38 | return (...args: unknown[]) => { 39 | // Level is an alias for INFO to support console.log drop-in 40 | if ( 41 | logger.minimumLogLevel !== undefined && 42 | logLevels.indexOf(logger.minimumLogLevel) > 43 | logLevels.indexOf(prop.toUpperCase()) 44 | ) { 45 | return 46 | } 47 | return func(...args) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /test/logger.spec.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 2 | /* eslint-disable no-console */ 3 | import { EventEmitter } from 'events' 4 | 5 | import { replaceAll } from '../src/strings' 6 | import { Logger, LOG_DELIMITER } from '../src/logger' 7 | 8 | import * as system from '../src/system' 9 | 10 | jest.mock('../src/system', () => { 11 | const fakeProcess: any = new EventEmitter() 12 | 13 | fakeProcess.exit = jest.fn() 14 | fakeProcess.stdout = { 15 | write: console.log.bind(console), 16 | } 17 | fakeProcess.version = 'local-test' 18 | fakeProcess.env = {} 19 | 20 | return { 21 | UNHANDLED_REJECTION_LISTENERS: 1, 22 | console: { 23 | log: jest.fn(), 24 | debug: jest.fn(), 25 | warn: jest.fn(), 26 | error: jest.fn(), 27 | }, 28 | process: fakeProcess, 29 | } 30 | }) 31 | 32 | const testToken = 33 | 'eyJraWQiOiIxTkJ3QTJDeWpKRmdDYU5SOXlXZW1jY2ZaaDFjZ19ET1haWXVWcS1oX2RFIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULjV5bFc5ekxBM0xGdkJVVldFY0F3NmdBVkl6SlRaUWJzRTE2S2VEUnpfT3MiLCJpc3MiOiJodHRwczovL25pa2UtcWEub2t0YXByZXZpZXcuY29tL29hdXRoMi9hdXNhMG1jb3JucFpMaTBDNDBoNyIsImF1ZCI6Imh0dHBzOi8vbmlrZS1xYS5va3RhcHJldmlldy5jb20iLCJpYXQiOjE1NTA1MzA5MjYsImV4cCI6MTU1MDUzNDUyNiwiY2lkIjoibmlrZS5uaWtldGVjaC50b2tlbi1nZW5lcmF0b3IiLCJ1aWQiOiIwMHU4Y2F1dGgxczhqN2ZFYjBoNyIsInNjcCI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiXSwic3ViIjoiVGltb3RoeS5LeWVAbmlrZS5jb20iLCJncm91cHMiOlsiQXBwbGljYXRpb24uVVMuRlRFLlVzZXJzIl19.nEfPoRPvrL1x6zsNzPWDN14AYV_AG62L0-I6etCGJlZZaOGFMnjBw4FLD-6y30MNdufwweVJ-RHApjDDaPVNQja6K7jaxBmZ1ryWy-JOO1IootRrF3aew5JlE6Q9CQ93I39uHsRCwWiy8tG_rYy7isv8ygz9xnCBRb3NQj7oBChJPvkwvO_DXD4MHde54aXLY6yryuHse-1MuEBXveZmCr6D2cUgHFNXFMwSwazXifHe8tJe2mItRq5l4zSZJQYDexm8Ww5XTwItiQZXV50dMF7F3D2A2tKwqF10CWy3ilw40BOEa3n0ptsDZmD4I3R0711vz_A21z3vYjqjt8pIxw' 34 | const tokenSignature = 35 | 'nEfPoRPvrL1x6zsNzPWDN14AYV_AG62L0-I6etCGJlZZaOGFMnjBw4FLD-6y30MNdufwweVJ-RHApjDDaPVNQja6K7jaxBmZ1ryWy-JOO1IootRrF3aew5JlE6Q9CQ93I39uHsRCwWiy8tG_rYy7isv8ygz9xnCBRb3NQj7oBChJPvkwvO_DXD4MHde54aXLY6yryuHse-1MuEBXveZmCr6D2cUgHFNXFMwSwazXifHe8tJe2mItRq5l4zSZJQYDexm8Ww5XTwItiQZXV50dMF7F3D2A2tKwqF10CWy3ilw40BOEa3n0ptsDZmD4I3R0711vz_A21z3vYjqjt8pIxw' 36 | const subSignature = 37 | 'ItRq5l4zSZJQYDexm8Ww5XTwItiQZXV50dMF7F3D2A2tKwqF10CWy3ilw40BOEa3n0ptsDZmD4I3R0711vz_A21z3vYjqjt8pIxw' 38 | 39 | afterEach(() => { 40 | jest.resetAllMocks() 41 | }) 42 | 43 | function getParsedLog( 44 | type: 'log' | 'debug' | 'warn' | 'error' = 'log', 45 | index = 0 46 | ): any { 47 | const logCall = getLog(type, index) 48 | return JSON.parse( 49 | replaceAll(logCall.substring(logCall.indexOf('|') + 1), LOG_DELIMITER, '') 50 | ) 51 | } 52 | 53 | function getLog( 54 | type: 'log' | 'debug' | 'warn' | 'error' = 'log', 55 | index = 0 56 | ): string { 57 | return (system.console[type] as jest.Mock).mock.calls[index][0] 58 | } 59 | 60 | describe('Logger', () => { 61 | test('returns logger', () => { 62 | const logger = Logger({ useGlobalErrorHandler: false }) 63 | 64 | expect(Object.keys(logger)).toEqual( 65 | expect.arrayContaining([ 66 | 'info', 67 | 'error', 68 | 'warn', 69 | 'debug', 70 | 'handler', 71 | 'setKey', 72 | 'setMinimumLogLevel', 73 | ]) 74 | ) 75 | }) 76 | test('writes info to console', () => { 77 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 78 | logger.info('test') 79 | logger.debug('bug') 80 | 81 | expect(system.console.log).toHaveBeenCalledWith( 82 | expect.stringContaining('test |') 83 | ) 84 | expect(system.console.log).toHaveBeenCalledWith( 85 | expect.stringContaining(LOG_DELIMITER) 86 | ) 87 | expect(system.console.debug).toHaveBeenCalledWith( 88 | expect.stringContaining('bug') 89 | ) 90 | }) 91 | 92 | test('stringifies objects with circular props', () => { 93 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 94 | const message: any = { 95 | name: 'tim', 96 | sub: { age: 30, sub2: { thing: 'stuff' } }, 97 | } 98 | 99 | message.circ = message 100 | logger.info(message) 101 | 102 | expect(system.console.log).toHaveBeenCalledWith( 103 | expect.stringContaining('"circ": "[Circular]"') 104 | ) 105 | }) 106 | 107 | test('includes detailed message', () => { 108 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 109 | logger.setKey('detail', 'value') 110 | logger.info('message') 111 | 112 | const logMessage = getParsedLog() 113 | expect(logMessage.message).toEqual('message') 114 | expect(logMessage.detail).toEqual('value') 115 | expect(logMessage.severity).toEqual('INFO') 116 | }) 117 | 118 | test('sets standard mdc keys for handler', async () => { 119 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 120 | 121 | await logger.handler(async () => { 122 | logger.setKey('detail', 'value') 123 | logger.info('handler message') 124 | })( 125 | {}, 126 | { 127 | functionName: 'test-run', 128 | awsRequestId: 'trace', 129 | requestContext: { requestId: 'requestId' }, 130 | } 131 | ) 132 | 133 | const logMessage = getParsedLog() 134 | 135 | expect(logMessage.message).toEqual('handler message') 136 | expect(logMessage.severity).toEqual('INFO') 137 | expect(logMessage.appName).toEqual('test-run') 138 | expect(logMessage.apigTraceId).toEqual('requestId') 139 | expect(logMessage.traceId).toEqual('trace') 140 | expect(logMessage.traceIndex).toEqual(0) 141 | expect(logMessage.date).toBeDefined() 142 | }) 143 | 144 | test('suppress messages below minimum severity', () => { 145 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 146 | logger.setMinimumLogLevel('INFO') 147 | logger.debug('skip') 148 | logger.info('include') 149 | 150 | const logCall = getLog() 151 | 152 | expect(logCall).toContain('include |') 153 | expect(logCall).toContain(LOG_DELIMITER) 154 | expect(system.console.log).toHaveBeenCalledTimes(1) 155 | expect(system.console.debug).toHaveBeenCalledTimes(0) 156 | }) 157 | 158 | test('suppress messages below minimum severity for errors', () => { 159 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 160 | logger.setMinimumLogLevel('WARN') 161 | logger.info('skip') 162 | logger.warn('include') 163 | 164 | const warnCall = getLog('warn') 165 | 166 | expect(warnCall).toContain('include |') 167 | expect(warnCall).toContain(LOG_DELIMITER) 168 | expect(system.console.warn).toHaveBeenCalledTimes(1) 169 | expect(system.console.log).toHaveBeenCalledTimes(0) 170 | }) 171 | 172 | test('suppress all messages for silent', () => { 173 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 174 | logger.setMinimumLogLevel('SILENT') 175 | logger.info('skip') 176 | logger.error('skip') 177 | expect(system.console.error).toHaveBeenCalledTimes(0) 178 | expect(system.console.log).toHaveBeenCalledTimes(0) 179 | }) 180 | 181 | test('sub-logger writes info to console', () => { 182 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 183 | logger.setKey('detail', 'value') 184 | 185 | const sub = logger.createSubLogger('db') 186 | sub.info('sub message') 187 | 188 | const logCall = getLog() 189 | expect(logCall).toContain('db sub message |') 190 | 191 | const logMessage = getParsedLog() 192 | expect(logMessage.message).toEqual('sub message') 193 | expect(logMessage.detail).toEqual('value') 194 | expect(logMessage.severity).toEqual('INFO') 195 | }) 196 | 197 | test('sub-logger respects parent minimum log level', () => { 198 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 199 | logger.setMinimumLogLevel('WARN') 200 | logger.setKey('detail', 'value') 201 | 202 | const sub = logger.createSubLogger('db') 203 | sub.info('skip') 204 | sub.warn('sub message') 205 | 206 | expect(system.console.log).toBeCalledTimes(0) 207 | expect(system.console.warn).toBeCalledTimes(1) 208 | 209 | const logCall = getLog('warn') 210 | expect(logCall).toContain('db sub message |') 211 | 212 | const logMessage = getParsedLog('warn') 213 | expect(logMessage.message).toEqual('sub message') 214 | expect(logMessage.detail).toEqual('value') 215 | expect(logMessage.severity).toEqual('WARN') 216 | }) 217 | 218 | test('registers global error handlers node12', () => { 219 | const fakeLambdaErrorHandler = jest.fn() 220 | system.process.removeAllListeners('uncaughtException') 221 | system.process.removeAllListeners('unhandledRejection') 222 | system.process.on('uncaughtException', fakeLambdaErrorHandler) 223 | system.process.on('unhandledRejection', fakeLambdaErrorHandler) 224 | Logger({ forceGlobalErrorHandler: true }) 225 | 226 | // @ts-ignore 227 | system.process.emit('uncaughtException', { stack: 'fake stack' }) 228 | // @ts-ignore 229 | system.process.emit('unhandledRejection', { stack: 'fake stack' }, true) 230 | 231 | process.removeAllListeners('uncaughtException') 232 | process.removeAllListeners('unhandledRejection') 233 | 234 | const logCall = getLog('error') 235 | expect(logCall).toMatch(/^uncaught exception/) 236 | expect(logCall).toContain('fake stack') 237 | 238 | const rejectCall = getLog('error', 1) 239 | expect(rejectCall).toMatch(/^unhandled rejection/) 240 | expect(rejectCall).toContain('fake stack') 241 | 242 | expect(() => Logger({ forceGlobalErrorHandler: true })).toThrow(/twice/) 243 | }) 244 | 245 | test('handles error handles in test mode', () => { 246 | Logger({ useGlobalErrorHandler: true, testMode: true }) 247 | Logger({ useGlobalErrorHandler: true, testMode: true }) 248 | }) 249 | 250 | test('triggers beforeHandler events', async () => { 251 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 252 | 253 | let calledHook = false 254 | logger.events.on('beforeHandler', (event, context) => { 255 | calledHook = true 256 | expect(event.isEvent).toBeDefined() 257 | expect(context.isContext).toBeDefined() 258 | }) 259 | 260 | await logger.handler(async () => { 261 | expect(calledHook).toBe(true) 262 | })({ isEvent: true }, { isContext: true }) 263 | 264 | expect.assertions(3) 265 | }) 266 | 267 | test('errors if handler is not async', async () => { 268 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 269 | 270 | await expect( 271 | logger.handler(() => { 272 | return {} 273 | })( 274 | {}, 275 | { 276 | functionName: 'test-run', 277 | awsRequestId: 'trace', 278 | requestContext: { requestId: 'requestId' }, 279 | } 280 | ) 281 | ).rejects.toThrow(/return a promise/) 282 | }) 283 | 284 | test('throws if setting reserved key', () => { 285 | const logger = Logger({ useGlobalErrorHandler: false, testMode: false }) 286 | 287 | expect(() => logger.setKey('message', 'test')).toThrow(/reserved/) 288 | }) 289 | 290 | test('uses TestFormatter in testMode', () => { 291 | const logger = Logger({ useGlobalErrorHandler: false, testMode: true }) 292 | logger.info('something') 293 | const logCall = getLog() 294 | expect(logCall).toEqual('something') 295 | }) 296 | 297 | test('redacts bearer tokens', () => { 298 | const logger = Logger({ 299 | useGlobalErrorHandler: false, 300 | useBearerRedactor: true, 301 | }) 302 | logger.info(`Bearer ${testToken}`) 303 | const logCall = getLog() 304 | expect(logCall).toContain('--redacted--') 305 | expect(logCall).not.toContain(testToken) 306 | expect(logCall).not.toContain(tokenSignature) 307 | expect(logCall).not.toContain(subSignature) 308 | }) 309 | 310 | test('redacts bearer tokens without "bearer"', () => { 311 | const logger = Logger({ 312 | useGlobalErrorHandler: false, 313 | useBearerRedactor: true, 314 | }) 315 | 316 | // redactor needs to be initialized 317 | logger.info(`Bearer ${testToken}`) 318 | // this is the log we check 319 | logger.info(`message "${testToken}"`) 320 | const logCall = getLog('log', 1) 321 | expect(logCall).toContain('--redacted--') 322 | expect(logCall).not.toContain(testToken) 323 | expect(logCall).not.toContain(tokenSignature) 324 | expect(logCall).not.toContain(subSignature) 325 | }) 326 | 327 | test('redacts bearer tokens in JSON', () => { 328 | const logger = Logger({ 329 | useGlobalErrorHandler: false, 330 | useBearerRedactor: true, 331 | }) 332 | logger.info( 333 | JSON.stringify({ headers: { Authorization: `Bearer ${testToken}` } }) 334 | ) 335 | const logCall = getLog() 336 | expect(logCall).toContain('--redacted--') 337 | expect(logCall).not.toContain(testToken) 338 | expect(logCall).not.toContain(tokenSignature) 339 | expect(logCall).not.toContain(subSignature) 340 | }) 341 | 342 | test('redacts bearer tokens in object', () => { 343 | const logger = Logger({ 344 | useGlobalErrorHandler: false, 345 | useBearerRedactor: true, 346 | }) 347 | logger.info({ headers: { Authorization: `Bearer ${testToken}` } }) 348 | const logCall = getLog() 349 | expect(logCall).toContain('--redacted--') 350 | expect(logCall).not.toContain(testToken) 351 | expect(logCall).not.toContain(tokenSignature) 352 | expect(logCall).not.toContain(subSignature) 353 | }) 354 | 355 | test('uses redactors', () => { 356 | const logger = Logger({ 357 | useGlobalErrorHandler: false, 358 | redactors: [ 359 | 'string', 360 | /regex/, 361 | (str) => str.replace('custom', '--removed--'), 362 | ], 363 | }) 364 | logger.info('string regex custom test') 365 | const logCall = getLog() 366 | expect(logCall).toMatch(/^--redacted-- --redacted-- --removed-- test/) 367 | }) 368 | }) 369 | -------------------------------------------------------------------------------- /test/wrapper.spec.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | import { wrapper as createLogger } from '../src/wrapper' 3 | 4 | describe('Wrapper', () => { 5 | test('when logger is not defined wrapper creates all methods', () => { 6 | const logger = createLogger(undefined) 7 | expect(typeof logger.error).toEqual('function') 8 | expect(typeof logger.warn).toEqual('function') 9 | expect(typeof logger.info).toEqual('function') 10 | expect(typeof logger.debug).toEqual('function') 11 | }) 12 | 13 | test('when logger is empty object wrapper creates all methods', () => { 14 | const logger = createLogger({}) 15 | expect(typeof logger.error).toEqual('function') 16 | expect(typeof logger.warn).toEqual('function') 17 | expect(typeof logger.info).toEqual('function') 18 | expect(typeof logger.debug).toEqual('function') 19 | }) 20 | 21 | test('when logger defines non-function methods wrapper uses noop', () => { 22 | const localLogger = { 23 | log: 'string', 24 | error: 32, 25 | warn: ['array'], 26 | info: 'another string', 27 | debug: () => { 28 | return 'log' 29 | }, 30 | } 31 | 32 | const logger = createLogger(localLogger) 33 | expect(typeof logger.error).toEqual('function') 34 | expect(typeof logger.warn).toEqual('function') 35 | expect(typeof logger.info).toEqual('function') 36 | expect(typeof logger.debug).toEqual('function') 37 | }) 38 | 39 | test('logger methods are used when they are defined', () => { 40 | const localLogger = { 41 | error: () => 'error', 42 | warn: () => 'warn', 43 | info: () => 'info', 44 | debug: () => 'debug', 45 | } 46 | 47 | const logger = createLogger(localLogger) 48 | expect(logger.error()).toEqual('error') 49 | expect(logger.warn()).toEqual('warn') 50 | expect(logger.info()).toEqual('info') 51 | expect(logger.debug()).toEqual('debug') 52 | }) 53 | 54 | test('allows console to be used as logger', () => { 55 | let called = false 56 | const original = console.info 57 | console.info = () => { 58 | called = true 59 | } 60 | const logger = createLogger(console) 61 | logger.info() 62 | expect(called).toEqual(true) 63 | console.info = original 64 | }) 65 | 66 | test('minimumLogLevel throws on invalid value', () => { 67 | expect(() => createLogger({ minimumLogLevel: 'fake' })).toThrow( 68 | /minimumLogLevel" must be one of/ 69 | ) 70 | expect(() => createLogger({ minimumLogLevel: 'INFO' })).not.toThrow() 71 | }) 72 | 73 | test('minimumLogLevel is respected', () => { 74 | const localLogger = { 75 | minimumLogLevel: 'INFO', 76 | error: () => 'error', 77 | warn: () => 'warn', 78 | info: () => 'info', 79 | debug: () => 'debug', 80 | } 81 | 82 | const logger = createLogger(localLogger) 83 | expect(logger.error()).toEqual('error') 84 | expect(logger.warn()).toEqual('warn') 85 | expect(logger.info()).toEqual('info') 86 | expect(logger.debug()).toEqual(undefined) 87 | 88 | localLogger.minimumLogLevel = 'ERROR' 89 | expect(logger.info()).toEqual(undefined) 90 | }) 91 | }) 92 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "ES2018", 5 | "module": "CommonJS", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": false, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "declarationDir": "lib/types", 14 | "outDir": "lib/", 15 | "typeRoots": ["node_modules/@types"] 16 | }, 17 | "include": ["src"] 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "sourceMap": true 5 | }, 6 | "include": ["src", "test"] 7 | } 8 | --------------------------------------------------------------------------------