Skip to content

Commit

Permalink
feat(logger): disable logs while testing with jest --silent in dev …
Browse files Browse the repository at this point in the history
…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 <[email protected]>

* 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 <[email protected]>

Co-authored-by: Andrea Amorosi <[email protected]>
  • Loading branch information
shdq and dreamorosi authored Nov 15, 2022
1 parent c37932d commit 6f0c307
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 34 deletions.
8 changes: 8 additions & 0 deletions docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
24 changes: 21 additions & 3 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -572,7 +573,7 @@ class Logger extends Utility implements ClassThatLogs {

return <number> this.powertoolLogData.sampleRateValue;
}

/**
* It returns true if the provided log level is valid.
*
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 7 additions & 7 deletions packages/logger/src/config/ConfigServiceInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down
22 changes: 11 additions & 11 deletions packages/logger/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down
39 changes: 33 additions & 6 deletions packages/logger/tests/unit/Logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand All @@ -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: {
Expand All @@ -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: {
Expand Down Expand Up @@ -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: {
Expand All @@ -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: {
Expand Down Expand Up @@ -1461,4 +1465,27 @@ describe('Class: Logger', () => {
});
});

});
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,
});
});
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -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"', () => {

Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion packages/logger/tests/unit/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ describe('Helper: createLogger function', () => {
getServiceName(): string {
return 'my-backend-service';
},
getDevMode(): boolean {
isDevMode(): boolean {
return false;
},
isValueTrue(): boolean {
Expand Down
2 changes: 1 addition & 1 deletion packages/logger/tests/unit/middleware/middy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ describe('Middy middleware', () => {
getServiceName(): string {
return 'my-backend-service';
},
getDevMode(): boolean {
isDevMode(): boolean {
return false;
},
isValueTrue(): boolean {
Expand Down

0 comments on commit 6f0c307

Please sign in to comment.