Skip to content

feat(logger): disable logs while testing with jest --silent in dev env #1165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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 @@ -574,7 +575,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 @@ -642,6 +643,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 @@ -699,7 +715,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 @@ -766,6 +782,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 @@ -1243,6 +1243,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 @@ -1261,7 +1262,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 @@ -1272,7 +1276,7 @@ describe('Class: Logger', () => {
customConfigService: undefined,
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
logIndentation: INDENTATION,
logFormatter: expect.any(PowertoolLogFormatter),
logLevel: 'DEBUG',
logLevelThresholds: {
Expand All @@ -1297,7 +1301,7 @@ describe('Class: Logger', () => {
customConfigService: undefined,
envVarsService: expect.any(EnvironmentVariablesService),
logEvent: false,
logIndentation: 0,
logIndentation: INDENTATION,
logFormatter: expect.any(PowertoolLogFormatter),
logLevel: 'DEBUG',
logLevelThresholds: {
Expand All @@ -1324,7 +1328,7 @@ describe('Class: Logger', () => {
customConfigService: 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', () => {
customConfigService: 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 @@ -310,7 +310,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