Skip to content

chore(maintenance): migrate logger utility to biome #2813

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 5 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 4 additions & 9 deletions packages/logger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
"build:cjs": "tsc --build tsconfig.json && echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json",
"build:esm": "tsc --build tsconfig.esm.json && echo '{ \"type\": \"module\" }' > lib/esm/package.json",
"build": "npm run build:esm & npm run build:cjs",
"lint": "eslint --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint-fix": "eslint --fix --ext .ts,.js --no-error-on-unmatched-pattern .",
"lint": "biome lint .",
"lint:fix": "biome check --write .",
"prepack": "node ../../.github/scripts/release_patch_package_json.js ."
},
"homepage": "https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/packages/logger#readme",
Expand Down Expand Up @@ -53,10 +53,7 @@
"lib/cjs/middleware/middy.d.ts",
"lib/esm/middleware/middy.d.ts"
],
"types": [
"lib/cjs/types/index.d.ts",
"lib/esm/types/index.d.ts"
]
"types": ["lib/cjs/types/index.d.ts", "lib/esm/types/index.d.ts"]
}
},
"types": "./lib/cjs/index.d.ts",
Expand All @@ -73,9 +70,7 @@
"optional": true
}
},
"files": [
"lib"
],
"files": ["lib"],
"repository": {
"type": "git",
"url": "git+https://github.com/aws-powertools/powertools-lambda-typescript.git"
Expand Down
25 changes: 11 additions & 14 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import { Console } from 'node:console';
import { randomInt } from 'node:crypto';
import { Utility } from '@aws-lambda-powertools/commons';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { Context, Handler } from 'aws-lambda';
import merge from 'lodash.merge';
import { Console } from 'node:console';
import { randomInt } from 'node:crypto';
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
import { LogJsonIndent } from './constants.js';
import { LogItem } from './formatter/LogItem.js';
import type { LogItem } from './formatter/LogItem.js';
import { PowertoolsLogFormatter } from './formatter/PowertoolsLogFormatter.js';
import type { ConfigServiceInterface } from './types/ConfigServiceInterface.js';
import type {
Environment,
LogAttributes,
LogFormatterInterface,
LogLevel,
LogLevelThresholds,
LogFormatterInterface,
} from './types/Log.js';
import type {
LogFunction,
ConstructorOptions,
CustomJsonReplacerFn,
InjectLambdaContextOptions,
LogFunction,
LogItemExtraInput,
LogItemMessage,
LoggerInterface,
PowertoolsLogData,
CustomJsonReplacerFn,
} from './types/Logger.js';

/**
Expand Down Expand Up @@ -442,10 +442,7 @@ class Logger extends Utility implements LoggerInterface {
options?: InjectLambdaContextOptions
): HandlerMethodDecorator {
return (_target, _propertyKey, descriptor) => {
/**
* The descriptor.value is the method this decorator decorates, it cannot be undefined.
*/
/* eslint-disable @typescript-eslint/no-non-null-assertion */
// biome-ignore lint/style/noNonNullAssertion: The descriptor.value is the method this decorator decorates, it cannot be undefined.
const originalMethod = descriptor.value!;

// eslint-disable-next-line @typescript-eslint/no-this-alias
Expand All @@ -463,8 +460,6 @@ class Logger extends Utility implements LoggerInterface {
let result: unknown;
try {
result = await originalMethod.apply(this, [event, context, callback]);
} catch (error) {
throw error;
} finally {
if (options?.clearState || options?.resetKeys) loggerRef.resetKeys();
}
Expand Down Expand Up @@ -697,9 +692,11 @@ class Logger extends Utility implements LoggerInterface {
const references = new WeakSet();

return (key, value) => {
// biome-ignore lint/style/noParameterAssign:
if (this.#jsonReplacerFn) value = this.#jsonReplacerFn?.(key, value);

if (value instanceof Error) {
// biome-ignore lint/style/noParameterAssign:
value = this.getLogFormatter().formatError(value);
}
if (typeof value === 'bigint') {
Expand Down Expand Up @@ -855,10 +852,10 @@ class Logger extends Utility implements LoggerInterface {
* @returns - The name of the log level
*/
private getLogLevelNameFromNumber(logLevel: number): Uppercase<LogLevel> {
let found;
let found: Uppercase<LogLevel> | undefined;
for (const [key, value] of Object.entries(this.logLevelThresholds)) {
if (value === logLevel) {
found = key;
found = key as Uppercase<LogLevel>;
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/logger/src/config/EnvironmentVariablesService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';
import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';
import type { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';

/**
* Class EnvironmentVariablesService
Expand Down
5 changes: 2 additions & 3 deletions packages/logger/src/formatter/LogFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
LogFormatterOptions,
} from '../types/Log.js';
import type { UnformattedAttributes } from '../types/Logger.js';
import { LogItem } from './LogItem.js';
import type { LogItem } from './LogItem.js';

/**
* This class defines and implements common methods for the formatting of log attributes.
Expand Down Expand Up @@ -92,8 +92,7 @@ abstract class LogFormatter implements LogFormatterInterface {
const stackLines = stack.split('\n');
const regex = /\(([^)]*?):(\d+?):(\d+?)\)\\?$/;

let i;
for (i = 0; i < stackLines.length; i++) {
for (let i = 0; i < stackLines.length; i++) {
const match = regex.exec(stackLines[i]);

if (Array.isArray(match)) {
Expand Down
14 changes: 7 additions & 7 deletions packages/logger/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Logger } from '../Logger.js';
import type { InjectLambdaContextOptions } from '../types/Logger.js';
import { LOGGER_KEY } from '@aws-lambda-powertools/commons';
import type {
MiddlewareLikeObj,
MiddyLikeRequest,
} from '@aws-lambda-powertools/commons/types';
import { Logger } from '../Logger.js';
import type { InjectLambdaContextOptions } from '../types/Logger.js';

/**
* A middy middleware that helps emitting CloudWatch EMF metrics in your logs.
Expand Down Expand Up @@ -35,7 +35,7 @@ const injectLambdaContext = (
target: Logger | Logger[],
options?: InjectLambdaContextOptions
): MiddlewareLikeObj => {
const loggers = target instanceof Array ? target : [target];
const loggers = Array.isArray(target) ? target : [target];
const isResetStateEnabled =
options && (options.clearState || options.resetKeys);

Expand All @@ -54,7 +54,7 @@ const injectLambdaContext = (
const injectLambdaContextBefore = async (
request: MiddyLikeRequest
): Promise<void> => {
loggers.forEach((logger: Logger) => {
for (const logger of loggers) {
if (isResetStateEnabled) {
setCleanupFunction(request);
}
Expand All @@ -64,14 +64,14 @@ const injectLambdaContext = (
request.context,
options
);
});
}
};

const injectLambdaContextAfterOrOnError = async (): Promise<void> => {
if (isResetStateEnabled) {
loggers.forEach((logger: Logger) => {
for (const logger of loggers) {
logger.resetKeys();
});
}
}
};

Expand Down
6 changes: 3 additions & 3 deletions packages/logger/src/types/Log.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { EnvironmentVariablesService } from '../config/EnvironmentVariablesService.js';
import type { LogLevel as LogLevelList } from '../constants.js';
import type { LogItem } from '../formatter/LogItem.js';
import type { UnformattedAttributes } from './Logger.js';
import { LogLevel } from '../constants.js';

type LogLevel =
| (typeof LogLevel)[keyof typeof LogLevel]
| Lowercase<(typeof LogLevel)[keyof typeof LogLevel]>;
| (typeof LogLevelList)[keyof typeof LogLevelList]
| Lowercase<(typeof LogLevelList)[keyof typeof LogLevelList]>;

type LogLevelThresholds = {
[key in Uppercase<LogLevel>]: number;
Expand Down
4 changes: 2 additions & 2 deletions packages/logger/src/types/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { Context } from 'aws-lambda';
import type { ConfigServiceInterface } from './ConfigServiceInterface.js';
import type {
Environment,
LogAttributes,
LogAttributesWithMessage,
LogLevel,
LogFormatterInterface,
LogLevel,
} from './Log.js';
import type { Context } from 'aws-lambda';

type LogFunction = {
[key in Exclude<Lowercase<LogLevel>, 'silent'>]: (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { APIGatewayAuthorizerResult, Context } from 'aws-lambda';
import middy from 'middy5';
import { Logger } from '../../src/index.js';
import { injectLambdaContext } from '../../src/middleware/middy.js';
import type { Context, APIGatewayAuthorizerResult } from 'aws-lambda';
import type { TestEvent, TestOutput } from '../helpers/types.js';
import middy from 'middy5';

const PERSISTENT_KEY = process.env.PERSISTENT_KEY || 'persistentKey';
const PERSISTENT_VALUE = process.env.PERSISTENT_VALUE || 'persistentValue';
Expand Down
6 changes: 3 additions & 3 deletions packages/logger/tests/e2e/basicFeatures.middy.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { join } from 'node:path';
/**
* Test logger basic features
*
* @group e2e/logger/basicFeatures
*/
import {
invokeFunction,
TestInvocationLogs,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import type { APIGatewayAuthorizerResult } from 'aws-lambda';
import { join } from 'node:path';
import { LoggerTestNodejsFunction } from '../helpers/resources.js';
import {
RESOURCE_NAME_PREFIX,
Expand All @@ -21,7 +21,7 @@ import {
commonEnvironmentVars,
} from './constants.js';

describe(`Logger E2E tests, basic functionalities middy usage`, () => {
describe('Logger E2E tests, basic functionalities middy usage', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Logger } from '../../src/index.js';
import type { Context } from 'aws-lambda';
import { Logger } from '../../src/index.js';
import type { LogLevel } from '../../src/types/index.js';
import { TestEvent, TestOutput } from '../helpers/types.js';
import type { TestEvent, TestOutput } from '../helpers/types.js';

const PERSISTENT_KEY = process.env.PERSISTENT_KEY || 'persistentKey';
const PERSISTENT_VALUE = process.env.ERSISTENT_VALUE || 'persistentValue';
Expand Down
8 changes: 4 additions & 4 deletions packages/logger/tests/e2e/childLogger.manual.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import { join } from 'node:path';
/**
* Test logger child logger
*
* @group e2e/logger/childLogger
*/
import {
invokeFunction,
TestInvocationLogs,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import { join } from 'node:path';
import { LoggerTestNodejsFunction } from '../helpers/resources.js';
import {
commonEnvironmentVars,
RESOURCE_NAME_PREFIX,
SETUP_TIMEOUT,
STACK_OUTPUT_LOG_GROUP,
TEARDOWN_TIMEOUT,
TEST_CASE_TIMEOUT,
commonEnvironmentVars,
} from './constants.js';

describe(`Logger E2E tests, child logger`, () => {
describe('Logger E2E tests, child logger', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Context } from 'aws-lambda';
import middy from 'middy4';
import { Logger } from '../../src/index.js';
import { injectLambdaContext } from '../../src/middleware/middy.js';
import type { TestEvent, TestOutput } from '../helpers/types.js';
import type { Context } from 'aws-lambda';
import middy from 'middy4';

const logger = new Logger();

Expand Down
6 changes: 3 additions & 3 deletions packages/logger/tests/e2e/logEventEnvVarSetting.middy.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { join } from 'node:path';
/**
* Test logger basic features
*
* @group e2e/logger/logEventEnvVarSetting
*/
import {
invokeFunction,
TestInvocationLogs,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import { join } from 'node:path';
import { LoggerTestNodejsFunction } from '../helpers/resources.js';
import {
RESOURCE_NAME_PREFIX,
Expand All @@ -18,7 +18,7 @@ import {
TEST_CASE_TIMEOUT,
} from './constants.js';

describe(`Logger E2E tests, log event via env var setting with middy`, () => {
describe('Logger E2E tests, log event via env var setting with middy', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import type { Context } from 'aws-lambda';
import { Logger } from '../../src/index.js';
import type { TestEvent, TestOutput } from '../helpers/types.js';
import type { Context } from 'aws-lambda';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';

const SAMPLE_RATE = parseFloat(process.env.SAMPLE_RATE || '0.1');
const SAMPLE_RATE = Number.parseFloat(process.env.SAMPLE_RATE || '0.1');
const LOG_MSG = process.env.LOG_MSG || 'Hello World';

const logger = new Logger({
Expand Down
8 changes: 4 additions & 4 deletions packages/logger/tests/e2e/sampleRate.decorator.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
/**
* Test logger sample rate feature
*
* @group e2e/logger/sampleRate
*/
import {
invokeFunction,
TestInvocationLogs,
TestStack,
invokeFunction,
} from '@aws-lambda-powertools/testing-utils';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { LoggerTestNodejsFunction } from '../helpers/resources.js';
import {
RESOURCE_NAME_PREFIX,
Expand All @@ -19,7 +19,7 @@ import {
TEST_CASE_TIMEOUT,
} from './constants.js';

describe(`Logger E2E tests, sample rate and injectLambdaContext()`, () => {
describe('Logger E2E tests, sample rate and injectLambdaContext()', () => {
const testStack = new TestStack({
stackNameProps: {
stackNamePrefix: RESOURCE_NAME_PREFIX,
Expand Down
4 changes: 2 additions & 2 deletions packages/logger/tests/helpers/resources.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { TestNodejsFunction } from '@aws-lambda-powertools/testing-utils/resources/lambda';
import type { TestStack } from '@aws-lambda-powertools/testing-utils';
import { CfnOutput } from 'aws-cdk-lib';
import { TestNodejsFunction } from '@aws-lambda-powertools/testing-utils/resources/lambda';
import type {
ExtraTestProps,
TestNodejsFunctionProps,
} from '@aws-lambda-powertools/testing-utils/types';
import { CfnOutput } from 'aws-cdk-lib';
import { commonEnvironmentVars } from '../e2e/constants';

interface LoggerExtraTestProps extends ExtraTestProps {
Expand Down
Loading