From 6f0c30728f31d60433b3afb6983c64110c28d27e Mon Sep 17 00:00:00 2001 From: Sergei Cherniaev Date: Tue, 15 Nov 2022 19:19:59 +0400 Subject: [PATCH] feat(logger): disable logs while testing with `jest --silent` in dev env (#1165) * feat(logger): disable logs while testing with jest --silent in dev env * refactor(logger): rename method * docs(logger): add testing section with jest --silent option, which is also suppresses logs (#1165) * Update docs/core/logger.md Co-authored-by: Andrea Amorosi * test(logger): add test for setConsole() method * test(logger): add comment for assertion * docs(logger): add an example of using POWERTOOLS_DEV with jest --silent * Update packages/logger/src/Logger.ts Co-authored-by: Andrea Amorosi Co-authored-by: Andrea Amorosi --- docs/core/logger.md | 8 ++++ packages/logger/src/Logger.ts | 24 ++++++++++-- .../src/config/ConfigServiceInterface.ts | 14 +++---- .../src/config/EnvironmentVariablesService.ts | 22 +++++------ packages/logger/tests/unit/Logger.test.ts | 39 ++++++++++++++++--- .../EnvironmentVariablesService.test.ts | 10 ++--- packages/logger/tests/unit/helpers.test.ts | 2 +- .../tests/unit/middleware/middy.test.ts | 2 +- 8 files changed, 87 insertions(+), 34 deletions(-) diff --git a/docs/core/logger.md b/docs/core/logger.md index 02d95a794f..4ec1d28dda 100644 --- a/docs/core/logger.md +++ b/docs/core/logger.md @@ -971,3 +971,11 @@ This is a Jest sample that provides the minimum information necessary for Logger !!! tip If you don't want to declare your own dummy Lambda Context, you can use [`ContextExamples.helloworldContext`](https://github.com/awslabs/aws-lambda-powertools-typescript/blob/main/packages/commons/src/samples/resources/contexts/hello-world.ts#L3-L16) from [`@aws-lambda-powertools/commons`](https://www.npmjs.com/package/@aws-lambda-powertools/commons). + +### Suppress logs with Jest + +When unit testing your code with [Jest](https://jestjs.io) you can use the `POWERTOOLS_DEV` environment variable in conjunction with the Jest `--silent` CLI option to suppress logs from Logger. + +```bash title="Disabling logs while testing with Jest" +export POWERTOOLS_DEV=true && npx jest --silent +``` diff --git a/packages/logger/src/Logger.ts b/packages/logger/src/Logger.ts index 1e6cac40b9..57b9ba1a57 100644 --- a/packages/logger/src/Logger.ts +++ b/packages/logger/src/Logger.ts @@ -113,7 +113,8 @@ import type { */ class Logger extends Utility implements ClassThatLogs { - private console = new Console({ stdout: process.stdout, stderr: process.stderr }); + // console is initialized in the constructor in setOptions() + private console!: Console; private customConfigService?: ConfigServiceInterface; @@ -572,7 +573,7 @@ class Logger extends Utility implements ClassThatLogs { return this.powertoolLogData.sampleRateValue; } - + /** * It returns true if the provided log level is valid. * @@ -640,6 +641,21 @@ class Logger extends Utility implements ClassThatLogs { }; } + /** + * It initializes console property as an instance of the internal version of Console() class (PR #748) + * or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value. + * + * @private + * @returns {void} + */ + private setConsole(): void { + if (!this.getEnvVarsService().isDevMode()) { + this.console = new Console({ stdout: process.stdout, stderr: process.stderr }); + } else { + this.console = console; + } + } + /** * Sets the Logger's customer config service instance, which will be used * to fetch environment variables. @@ -697,7 +713,7 @@ class Logger extends Utility implements ClassThatLogs { * @returns {void} */ private setLogIndentation(): void { - if (this.getEnvVarsService().getDevMode()) { + if (this.getEnvVarsService().isDevMode()) { this.logIndentation = LogJsonIndent.PRETTY; } } @@ -764,6 +780,8 @@ class Logger extends Utility implements ClassThatLogs { } = options; this.setEnvVarsService(); + // order is important, it uses EnvVarsService() + this.setConsole(); this.setCustomConfigService(customConfigService); this.setLogLevel(logLevel); this.setSampleRateValue(sampleRateValue); diff --git a/packages/logger/src/config/ConfigServiceInterface.ts b/packages/logger/src/config/ConfigServiceInterface.ts index 43f25d3649..d66d4e9f85 100644 --- a/packages/logger/src/config/ConfigServiceInterface.ts +++ b/packages/logger/src/config/ConfigServiceInterface.ts @@ -22,13 +22,6 @@ interface ConfigServiceInterface { */ getCurrentEnvironment(): string - /** - * It returns the value of the POWERTOOLS_DEV environment variable. - * - * @returns {boolean} - */ - getDevMode(): boolean - /** * It returns the value of the POWERTOOLS_LOGGER_LOG_EVENT environment variable. * @@ -57,6 +50,13 @@ interface ConfigServiceInterface { */ getServiceName(): string + /** + * It returns the value of the POWERTOOLS_DEV environment variable. + * + * @returns {boolean} + */ + isDevMode(): boolean + /** * It returns true if the string value represents a boolean true value. * diff --git a/packages/logger/src/config/EnvironmentVariablesService.ts b/packages/logger/src/config/EnvironmentVariablesService.ts index fab7ec9fc8..52fe910784 100644 --- a/packages/logger/src/config/EnvironmentVariablesService.ts +++ b/packages/logger/src/config/EnvironmentVariablesService.ts @@ -46,17 +46,6 @@ class EnvironmentVariablesService extends CommonEnvironmentVariablesService impl return this.get(this.currentEnvironmentVariable); } - /** - * It returns the value of the POWERTOOLS_DEV environment variable. - * - * @returns {boolean} - */ - public getDevMode(): boolean { - const value = this.get(this.devModeVariable); - - return this.isValueTrue(value); - } - /** * It returns the value of the AWS_LAMBDA_FUNCTION_MEMORY_SIZE environment variable. * @@ -117,6 +106,17 @@ class EnvironmentVariablesService extends CommonEnvironmentVariablesService impl return (value && value.length > 0) ? Number(value) : undefined; } + /** + * It returns true if the POWERTOOLS_DEV environment variable is set to truthy value. + * + * @returns {boolean} + */ + public isDevMode(): boolean { + const value = this.get(this.devModeVariable); + + return this.isValueTrue(value); + } + /** * It returns true if the string value represents a boolean true value. * diff --git a/packages/logger/tests/unit/Logger.test.ts b/packages/logger/tests/unit/Logger.test.ts index aead56b637..e5fe9b39b7 100644 --- a/packages/logger/tests/unit/Logger.test.ts +++ b/packages/logger/tests/unit/Logger.test.ts @@ -1239,6 +1239,7 @@ describe('Class: Logger', () => { test('when called, it returns a DISTINCT clone of the logger instance', () => { // Prepare + const INDENTATION = LogJsonIndent.COMPACT; const parentLogger = new Logger(); // Act @@ -1257,7 +1258,10 @@ describe('Class: Logger', () => { // Assess expect(parentLogger === childLogger).toBe(false); - expect(parentLogger).toEqual(childLogger); + expect(childLogger).toEqual({ + ...parentLogger, + console: expect.any(Console), + }); expect(parentLogger === childLoggerWithPermanentAttributes).toBe(false); expect(parentLogger === childLoggerWithSampleRateEnabled).toBe(false); expect(parentLogger === childLoggerWithErrorLogLevel).toBe(false); @@ -1269,7 +1273,7 @@ describe('Class: Logger', () => { defaultServiceName: 'service_undefined', envVarsService: expect.any(EnvironmentVariablesService), logEvent: false, - logIndentation: 0, + logIndentation: INDENTATION, logFormatter: expect.any(PowertoolLogFormatter), logLevel: 'DEBUG', logLevelThresholds: { @@ -1295,7 +1299,7 @@ describe('Class: Logger', () => { defaultServiceName: 'service_undefined', envVarsService: expect.any(EnvironmentVariablesService), logEvent: false, - logIndentation: 0, + logIndentation: INDENTATION, logFormatter: expect.any(PowertoolLogFormatter), logLevel: 'DEBUG', logLevelThresholds: { @@ -1323,7 +1327,7 @@ describe('Class: Logger', () => { defaultServiceName: 'service_undefined', envVarsService: expect.any(EnvironmentVariablesService), logEvent: false, - logIndentation: 0, + logIndentation: INDENTATION, logFormatter: expect.any(PowertoolLogFormatter), logLevel: 'DEBUG', logLevelThresholds: { @@ -1349,7 +1353,7 @@ describe('Class: Logger', () => { defaultServiceName: 'service_undefined', envVarsService: expect.any(EnvironmentVariablesService), logEvent: false, - logIndentation: 0, + logIndentation: INDENTATION, logFormatter: expect.any(PowertoolLogFormatter), logLevel: 'ERROR', logLevelThresholds: { @@ -1461,4 +1465,27 @@ describe('Class: Logger', () => { }); }); -}); \ No newline at end of file + describe('Method: setConsole()', () => { + + test('When the `POWERTOOLS_DEV` env var is SET console object is set to the global node console otherwise to the instance of the internal version of console', () => { + + // Prepare + const logger = new Logger(); + process.env.POWERTOOLS_DEV = 'true'; + const devLogger = new Logger(); + + // Assess + expect(devLogger).toEqual({ + ...devLogger, + console: console, + }); + // since instances of a class are not equal objects, + // we assert the opposite – console is not the global node object + expect(logger).not.toEqual({ + ...logger, + console: console, + }); + }); + }); + +}); diff --git a/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts b/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts index ccaf0084bf..b9aa387614 100644 --- a/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts +++ b/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts @@ -181,7 +181,7 @@ describe('Class: EnvironmentVariablesService', () => { }); - describe('Method: getDevMode', () => { + describe('Method: isDevMode', () => { test('It returns true if the environment variable POWERTOOLS_DEV is "true"', () => { @@ -190,7 +190,7 @@ describe('Class: EnvironmentVariablesService', () => { const service = new EnvironmentVariablesService(); // Act - const value = service.getDevMode(); + const value = service.isDevMode(); // Assess expect(value).toEqual(true); @@ -203,7 +203,7 @@ describe('Class: EnvironmentVariablesService', () => { const service = new EnvironmentVariablesService(); // Act - const value = service.getDevMode(); + const value = service.isDevMode(); // Assess expect(value).toEqual(false); @@ -216,7 +216,7 @@ describe('Class: EnvironmentVariablesService', () => { const service = new EnvironmentVariablesService(); // Act - const value = service.getDevMode(); + const value = service.isDevMode(); // Assess expect(value).toEqual(false); @@ -229,7 +229,7 @@ describe('Class: EnvironmentVariablesService', () => { const service = new EnvironmentVariablesService(); // Act - const value = service.getDevMode(); + const value = service.isDevMode(); // Assess expect(value).toEqual(false); diff --git a/packages/logger/tests/unit/helpers.test.ts b/packages/logger/tests/unit/helpers.test.ts index a185e980d8..3a4298421b 100644 --- a/packages/logger/tests/unit/helpers.test.ts +++ b/packages/logger/tests/unit/helpers.test.ts @@ -314,7 +314,7 @@ describe('Helper: createLogger function', () => { getServiceName(): string { return 'my-backend-service'; }, - getDevMode(): boolean { + isDevMode(): boolean { return false; }, isValueTrue(): boolean { diff --git a/packages/logger/tests/unit/middleware/middy.test.ts b/packages/logger/tests/unit/middleware/middy.test.ts index 88e37b9fce..8ec29fb957 100644 --- a/packages/logger/tests/unit/middleware/middy.test.ts +++ b/packages/logger/tests/unit/middleware/middy.test.ts @@ -336,7 +336,7 @@ describe('Middy middleware', () => { getServiceName(): string { return 'my-backend-service'; }, - getDevMode(): boolean { + isDevMode(): boolean { return false; }, isValueTrue(): boolean {