Skip to content

feat(metrics): add ability to pass custom logger #3057

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 9 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion layers/tests/e2e/layerPublisher.class.test.functionCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { SSMClient } from '@aws-sdk/client-ssm';
const logger = new Logger({
logLevel: 'DEBUG',
});
const metrics = new Metrics();
const metrics = new Metrics({ logger });
const tracer = new Tracer();

// Instantiating these clients and the respective providers/persistence layers
Expand Down
11 changes: 3 additions & 8 deletions layers/tests/e2e/layerPublisher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,10 @@ describe('Layers E2E tests', () => {
const logs = invocationLogs.getFunctionLogs('WARN');

expect(logs.length).toBe(1);
expect(
invocationLogs.doesAnyFunctionLogsContains(
/Namespace should be defined, default used/,
'WARN'
)
).toBe(true);
/* expect(logEntry.message).toEqual(
const logEntry = TestInvocationLogs.parseFunctionLog(logs[0]);
expect(logEntry.message).toEqual(
'Namespace should be defined, default used'
); */
);
}
);

Expand Down
17 changes: 17 additions & 0 deletions packages/commons/src/types/GenericLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// biome-ignore lint/suspicious/noExplicitAny: We intentionally use `any` here to represent any type of data and keep the logger is as flexible as possible.
type Anything = any[];

/**
* Interface for a generic logger object.
*
* This interface is used to define the shape of a logger object that can be passed to a Powertools for AWS utility.
*
* It can be an instance of Logger from Powertools for AWS, or any other logger that implements the same methods.
*/
export interface GenericLogger {
trace?: (...content: Anything) => void;
debug: (...content: Anything) => void;
info: (...content: Anything) => void;
warn: (...content: Anything) => void;
error: (...content: Anything) => void;
}
1 change: 1 addition & 0 deletions packages/commons/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type {
MiddlewareFn,
CleanupFunction,
} from './middy.js';
export type { GenericLogger } from './GenericLogger.js';
export type { SdkClient, MiddlewareArgsLike } from './awsSdk.js';
export type {
JSONPrimitive,
Expand Down
27 changes: 23 additions & 4 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Console } from 'node:console';
import { Utility } from '@aws-lambda-powertools/commons';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type {
GenericLogger,
HandlerMethodDecorator,
} from '@aws-lambda-powertools/commons/types';
import type { Callback, Context, Handler } from 'aws-lambda';
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
import {
Expand Down Expand Up @@ -159,6 +162,13 @@ class Metrics extends Utility implements MetricsInterface {
*/
private functionName?: string;

/**
* Custom logger object used for emitting debug, warning, and error messages.
*
* Note that this logger is not used for emitting metrics which are emitted to standard output using the `Console` object.
*/
readonly #logger: GenericLogger;

/**
* Flag indicating if this is a single metric instance
* @default false
Expand Down Expand Up @@ -193,6 +203,7 @@ class Metrics extends Utility implements MetricsInterface {

this.dimensions = {};
this.setOptions(options);
this.#logger = options.logger || this.console;
}

/**
Expand Down Expand Up @@ -439,6 +450,13 @@ class Metrics extends Utility implements MetricsInterface {
this.storedMetrics = {};
}

/**
* Check if there are stored metrics in the buffer.
*/
public hasStoredMetrics(): boolean {
return Object.keys(this.storedMetrics).length > 0;
}

/**
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
Expand Down Expand Up @@ -539,9 +557,9 @@ class Metrics extends Utility implements MetricsInterface {
* ```
*/
public publishStoredMetrics(): void {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
const hasMetrics = this.hasStoredMetrics();
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn(
this.#logger.warn(
'No application metrics to publish. The cold-start metric may be published if enabled. ' +
'If application metrics should never be empty, consider using `throwOnEmptyMetrics`'
);
Expand Down Expand Up @@ -584,7 +602,7 @@ class Metrics extends Utility implements MetricsInterface {
}

if (!this.namespace)
console.warn('Namespace should be defined, default used');
this.#logger.warn('Namespace should be defined, default used');

// We reduce the stored metrics to a single object with the metric
// name as the key and the value as the value.
Expand Down Expand Up @@ -731,6 +749,7 @@ class Metrics extends Utility implements MetricsInterface {
serviceName: this.dimensions.service,
defaultDimensions: this.defaultDimensions,
singleMetric: true,
logger: this.#logger,
});
}

Expand Down
14 changes: 13 additions & 1 deletion packages/metrics/src/types/Metrics.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type {
GenericLogger,
HandlerMethodDecorator,
} from '@aws-lambda-powertools/commons/types';
import type {
MetricResolution as MetricResolutions,
MetricUnit as MetricUnits,
Expand Down Expand Up @@ -57,6 +60,15 @@ type MetricsOptions = {
* @see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}
*/
defaultDimensions?: Dimensions;
/**
* Logger object to be used for emitting debug, warning, and error messages.
*
* If not provided, debug messages will be suppressed, and warning and error messages will be sent to stdout.
*
* Note that EMF metrics are always sent directly to stdout, regardless of the logger
* to avoid compatibility issues with custom loggers.
*/
logger?: GenericLogger;
};

/**
Expand Down
27 changes: 21 additions & 6 deletions packages/metrics/tests/unit/Metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ jest.mock('node:console', () => ({
...jest.requireActual('node:console'),
Console: jest.fn().mockImplementation(() => ({
log: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
})),
}));
jest.spyOn(console, 'warn').mockImplementation(() => ({}));
Expand Down Expand Up @@ -1254,9 +1256,17 @@ describe('Class: Metrics', () => {
describe('Methods: publishStoredMetrics', () => {
test('it should log warning if no metrics are added & throwOnEmptyMetrics is false', () => {
// Prepare
const metrics: Metrics = new Metrics({ namespace: TEST_NAMESPACE });
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
const customLogger = {
warn: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
info: jest.fn(),
};
const metrics: Metrics = new Metrics({
namespace: TEST_NAMESPACE,
logger: customLogger,
});
const consoleWarnSpy = jest.spyOn(customLogger, 'warn');

// Act
metrics.publishStoredMetrics();
Expand All @@ -1266,7 +1276,6 @@ describe('Class: Metrics', () => {
expect(consoleWarnSpy).toHaveBeenCalledWith(
'No application metrics to publish. The cold-start metric may be published if enabled. If application metrics should never be empty, consider using `throwOnEmptyMetrics`'
);
expect(consoleLogSpy).not.toHaveBeenCalled();
});

test('it should call serializeMetrics && log the stringified return value of serializeMetrics', () => {
Expand Down Expand Up @@ -1355,8 +1364,14 @@ describe('Class: Metrics', () => {
test('it should print warning, if no namespace provided in constructor or environment variable', () => {
// Prepare
process.env.POWERTOOLS_METRICS_NAMESPACE = '';
const metrics: Metrics = new Metrics();
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
const customLogger = {
warn: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
info: jest.fn(),
};
const metrics: Metrics = new Metrics({ logger: customLogger });
const consoleWarnSpy = jest.spyOn(customLogger, 'warn');

// Act
metrics.serializeMetrics();
Expand Down
3 changes: 3 additions & 0 deletions packages/metrics/tests/unit/middleware/middy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ jest.mock('node:console', () => ({
...jest.requireActual('node:console'),
Console: jest.fn().mockImplementation(() => ({
log: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
})),
}));
jest.spyOn(console, 'warn').mockImplementation(() => ({}));
Expand Down Expand Up @@ -68,6 +70,7 @@ describe('Middy middleware', () => {
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
logger: console,
});
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
const handler = middy(async (): Promise<void> => undefined).use(
Expand Down
71 changes: 0 additions & 71 deletions packages/metrics/tests/unit/repro.test.ts

This file was deleted.