Skip to content

feat(metrics): disable metrics with POWERTOOLS_METRICS_DISABLED #3351

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

Merged
merged 4 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,11 @@ class Metrics extends Utility implements MetricsInterface {
*/
private storedMetrics: StoredMetrics = {};

/**
* Whether to disable metrics
*/
private disabled = false;

/**
* Custom timestamp for the metrics
*/
Expand Down Expand Up @@ -480,6 +485,13 @@ class Metrics extends Utility implements MetricsInterface {
return Object.keys(this.storedMetrics).length > 0;
}

/**
* Whether metrics are disabled.
*/
public isDisabled(): boolean {
return this.disabled;
}

/**
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
Expand Down Expand Up @@ -587,8 +599,14 @@ class Metrics extends Utility implements MetricsInterface {
'If application metrics should never be empty, consider using `throwOnEmptyMetrics`'
);
}
const emfOutput = this.serializeMetrics();
hasMetrics && this.console.log(JSON.stringify(emfOutput));

if (!this.disabled) {
const emfOutput = this.serializeMetrics();
hasMetrics && this.console.log(JSON.stringify(emfOutput));
} else {
// TODO log warning that metrics are disabled?
}

this.clearMetrics();
this.clearDimensions();
this.clearMetadata();
Expand Down Expand Up @@ -921,6 +939,17 @@ class Metrics extends Utility implements MetricsInterface {
this.getEnvVarsService().getNamespace()) as string;
}

/**
* Set the disbaled flag based on the environment variables `POWERTOOLS_METRICS_DISABLED` and `POWERTOOLS_DEV`.
*/
private setDisabled(): void {
this.disabled =
this.getEnvVarsService().isDevMode() ||
this.getEnvVarsService().getMetricsDisabled();

// TODO if POWERTOOLS_METRICS_DISABLED is set to false, and dev mode is enabled, then POWERTOOLS_METRICS_DISABLED takes precedence and the utility stays enabled.
}

/**
* Set the options to be used by the Metrics instance.
*
Expand All @@ -943,6 +972,7 @@ class Metrics extends Utility implements MetricsInterface {
this.setNamespace(namespace);
this.setService(serviceName);
this.setDefaultDimensions(defaultDimensions);
this.setDisabled();
this.isSingleMetric = singleMetric || false;

return this;
Expand Down
11 changes: 11 additions & 0 deletions packages/metrics/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,23 @@ class EnvironmentVariablesService
{
private namespaceVariable = 'POWERTOOLS_METRICS_NAMESPACE';

private disabledVariable = 'POWERTOOLS_METRICS_DISABLED';

/**
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/
public getNamespace(): string {
return this.get(this.namespaceVariable);
}

/**
* Get the value of the `POWERTOOLS_METRICS_DISABLED` environment variable.
*/
public getMetricsDisabled(): boolean {
const value = this.get(this.disabledVariable);

return this.isValueTrue(value);
}
}

export { EnvironmentVariablesService };
49 changes: 49 additions & 0 deletions packages/metrics/tests/unit/Metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,29 @@ describe('Class: Metrics', () => {
expect(consoleLogSpy).toBeCalledWith(JSON.stringify(mockData));
});

test('it should not log anything if metrics are disabled', () => {
// Prepare
process.env.POWERTOOLS_METRICS_DISABLED = 'true';
const customLogger = {
log: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
info: jest.fn(),
};
const metrics: Metrics = new Metrics({
namespace: TEST_NAMESPACE,
logger: customLogger,
});
const consoleLogSpy = jest.spyOn(customLogger, 'log');

// Act
metrics.publishStoredMetrics();

// Assess
expect(consoleLogSpy).toHaveBeenCalledTimes(0);
});

test('it should call clearMetrics function', () => {
// Prepare
const metrics: Metrics = new Metrics({ namespace: TEST_NAMESPACE });
Expand Down Expand Up @@ -2343,6 +2366,32 @@ describe('Class: Metrics', () => {
});
});

describe('Method: isDisabled', () => {
it('should be enabled by default', () => {
const metrics: Metrics = new Metrics({ namespace: TEST_NAMESPACE });

// Act & Assess
expect(metrics.isDisabled()).toBe(false);
});

it('should be disabled if POWERTOOLS_DEV is set to true', () => {
process.env.POWERTOOLS_DEV = 'true';
const metrics: Metrics = new Metrics({ namespace: TEST_NAMESPACE });

// Act & Assess
expect(metrics.isDisabled()).toBe(true);
});

it('should be disabled if POWERTOOLS_METRICS_DISABLED is set to true', () => {
// Prepare
process.env.POWERTOOLS_METRICS_DISABLED = 'true';
const metrics: Metrics = new Metrics({ namespace: TEST_NAMESPACE });

// Act & Assess
expect(metrics.isDisabled()).toBe(true);
});
});

describe('Method: setTimestamp', () => {
const testCases = [
{
Expand Down