Skip to content

Commit b2fcd90

Browse files
jaimellamasijllamasidreamorosi
authored
refactor(logger): replace EnvironmentVariablesService class with helper functions (aws-powertools#4251)
Co-authored-by: Jaime Llamas <jaime.llamas@aircall.io> Co-authored-by: Andrea Amorosi <dreamorosi@gmail.com>
1 parent 1a86ef6 commit b2fcd90

File tree

9 files changed

+121
-446
lines changed

9 files changed

+121
-446
lines changed

packages/logger/src/Logger.ts

Lines changed: 59 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,15 @@ import type {
66
HandlerMethodDecorator,
77
SyncHandler,
88
} from '@aws-lambda-powertools/commons/types';
9+
import {
10+
getBooleanFromEnv,
11+
getNumberFromEnv,
12+
getStringFromEnv,
13+
getXRayTraceIdFromEnv,
14+
isDevMode,
15+
} from '@aws-lambda-powertools/commons/utils/env';
916
import type { Context, Handler } from 'aws-lambda';
1017
import merge from 'lodash.merge';
11-
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
1218
import {
1319
LogJsonIndent,
1420
LogLevelThreshold,
@@ -112,10 +118,6 @@ class Logger extends Utility implements LoggerInterface {
112118
* Custom config service instance used to configure the logger.
113119
*/
114120
private customConfigService?: ConfigServiceInterface;
115-
/**
116-
* Environment variables service instance used to fetch environment variables.
117-
*/
118-
private envVarsService = new EnvironmentVariablesService();
119121
/**
120122
* Whether to print the Lambda invocation event in the logs.
121123
*/
@@ -850,7 +852,7 @@ class Logger extends Utility implements LoggerInterface {
850852
const unformattedBaseAttributes = {
851853
logLevel: this.getLogLevelNameFromNumber(logLevel),
852854
timestamp: new Date(),
853-
xRayTraceId: this.envVarsService.getXrayTraceId(),
855+
xRayTraceId: getXRayTraceIdFromEnv(),
854856
...this.getPowertoolsLogData(),
855857
message: '',
856858
};
@@ -975,13 +977,6 @@ class Logger extends Utility implements LoggerInterface {
975977
return this.customConfigService;
976978
}
977979

978-
/**
979-
* Get the instance of a service that fetches environment variables.
980-
*/
981-
private getEnvVarsService(): EnvironmentVariablesService {
982-
return this.envVarsService as EnvironmentVariablesService;
983-
}
984-
985980
/**
986981
* Get the instance of a service that formats the structure of a
987982
* log item's keys and values in the desired way.
@@ -1081,7 +1076,7 @@ class Logger extends Utility implements LoggerInterface {
10811076
input: LogItemMessage,
10821077
extraInput: LogItemExtraInput
10831078
): void {
1084-
const traceId = this.envVarsService.getXrayTraceId();
1079+
const traceId = getXRayTraceIdFromEnv();
10851080
if (traceId !== undefined && this.shouldBufferLog(traceId, logLevel)) {
10861081
try {
10871082
this.bufferLogItem(
@@ -1125,7 +1120,7 @@ class Logger extends Utility implements LoggerInterface {
11251120
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
11261121
*/
11271122
private setConsole(): void {
1128-
if (!this.getEnvVarsService().isDevMode()) {
1123+
if (!isDevMode()) {
11291124
this.console = new Console({
11301125
stdout: process.stdout,
11311126
stderr: process.stderr,
@@ -1190,9 +1185,21 @@ class Logger extends Utility implements LoggerInterface {
11901185

11911186
return;
11921187
}
1193-
const envVarsValue = this.getEnvVarsService()?.getLogLevel()?.toUpperCase();
1194-
if (this.isValidLogLevel(envVarsValue)) {
1195-
this.logLevel = LogLevelThreshold[envVarsValue];
1188+
1189+
const logLevelVariable = getStringFromEnv({
1190+
key: 'POWERTOOLS_LOG_LEVEL',
1191+
defaultValue: '',
1192+
});
1193+
const logLevelVariableAlias = getStringFromEnv({
1194+
key: 'LOG_LEVEL',
1195+
defaultValue: '',
1196+
});
1197+
1198+
const logLevelValue =
1199+
logLevelVariable !== '' ? logLevelVariable : logLevelVariableAlias;
1200+
1201+
if (this.isValidLogLevel(logLevelValue)) {
1202+
this.logLevel = LogLevelThreshold[logLevelValue];
11961203
this.#initialLogLevel = this.logLevel;
11971204

11981205
return;
@@ -1212,8 +1219,15 @@ class Logger extends Utility implements LoggerInterface {
12121219
const constructorValue = sampleRateValue;
12131220
const customConfigValue =
12141221
this.getCustomConfigService()?.getSampleRateValue();
1215-
const envVarsValue = this.getEnvVarsService().getSampleRateValue();
1216-
for (const value of [constructorValue, customConfigValue, envVarsValue]) {
1222+
const sampleRateEnvVariable = getNumberFromEnv({
1223+
key: 'POWERTOOLS_LOGGER_SAMPLE_RATE',
1224+
defaultValue: 0,
1225+
});
1226+
for (const value of [
1227+
constructorValue,
1228+
customConfigValue,
1229+
sampleRateEnvVariable,
1230+
]) {
12171231
if (this.isValidSampleRate(value)) {
12181232
this.#debugLogSampling.sampleRateValue = value;
12191233
this.powertoolsLogData.sampleRateValue = value;
@@ -1236,9 +1250,10 @@ class Logger extends Utility implements LoggerInterface {
12361250
* the event passed to the Lambda function handler should be logged or not.
12371251
*/
12381252
private setLogEvent(): void {
1239-
if (this.getEnvVarsService().getLogEvent()) {
1240-
this.logEvent = true;
1241-
}
1253+
this.logEvent = getBooleanFromEnv({
1254+
key: 'POWERTOOLS_LOGGER_LOG_EVENT',
1255+
defaultValue: false,
1256+
});
12421257
}
12431258

12441259
/**
@@ -1255,7 +1270,6 @@ class Logger extends Utility implements LoggerInterface {
12551270
this.logFormatter =
12561271
logFormatter ??
12571272
new PowertoolsLogFormatter({
1258-
envVarsService: this.getEnvVarsService(),
12591273
logRecordOrder,
12601274
});
12611275
}
@@ -1265,7 +1279,7 @@ class Logger extends Utility implements LoggerInterface {
12651279
* add JSON indentation for pretty printing logs.
12661280
*/
12671281
private setLogIndentation(): void {
1268-
if (this.getEnvVarsService().isDevMode()) {
1282+
if (isDevMode()) {
12691283
this.logIndentation = LogJsonIndent.PRETTY;
12701284
}
12711285
}
@@ -1307,7 +1321,13 @@ class Logger extends Utility implements LoggerInterface {
13071321
);
13081322

13091323
// configurations that affect Logger behavior
1310-
const AlcLogLevel = this.getEnvVarsService().getAwsLogLevel();
1324+
const lambdaLogLevel = getStringFromEnv({
1325+
key: 'AWS_LAMBDA_LOG_LEVEL',
1326+
defaultValue: '',
1327+
});
1328+
const AlcLogLevel =
1329+
lambdaLogLevel === 'FATAL' ? 'CRITICAL' : lambdaLogLevel;
1330+
13111331
if (this.isValidLogLevel(AlcLogLevel)) {
13121332
this.#alcLogLevel = AlcLogLevel;
13131333
}
@@ -1340,15 +1360,23 @@ class Logger extends Utility implements LoggerInterface {
13401360
persistentKeys?: ConstructorOptions['persistentKeys']
13411361
): void {
13421362
this.addToPowertoolsLogData({
1343-
awsRegion: this.getEnvVarsService().getAwsRegion(),
1363+
awsRegion: getStringFromEnv({
1364+
key: 'AWS_REGION',
1365+
}),
13441366
environment:
13451367
environment ||
13461368
this.getCustomConfigService()?.getCurrentEnvironment() ||
1347-
this.getEnvVarsService().getCurrentEnvironment(),
1369+
getStringFromEnv({
1370+
key: 'ENVIRONMENT',
1371+
defaultValue: '',
1372+
}),
13481373
serviceName:
13491374
serviceName ||
13501375
this.getCustomConfigService()?.getServiceName() ||
1351-
this.getEnvVarsService().getServiceName() ||
1376+
getStringFromEnv({
1377+
key: 'POWERTOOLS_SERVICE_NAME',
1378+
defaultValue: '',
1379+
}) ||
13521380
this.defaultServiceName,
13531381
});
13541382
persistentKeys && this.appendPersistentKeys(persistentKeys);
@@ -1433,7 +1461,7 @@ class Logger extends Utility implements LoggerInterface {
14331461
* your function throws an error.
14341462
*/
14351463
public flushBuffer(): void {
1436-
const traceId = this.envVarsService.getXrayTraceId();
1464+
const traceId = getXRayTraceIdFromEnv();
14371465
if (traceId === undefined) {
14381466
return;
14391467
}
@@ -1477,7 +1505,7 @@ class Logger extends Utility implements LoggerInterface {
14771505
* Empties the buffer for the current request
14781506
*/
14791507
public clearBuffer(): void {
1480-
const traceId = this.envVarsService.getXrayTraceId();
1508+
const traceId = getXRayTraceIdFromEnv();
14811509
if (traceId === undefined) {
14821510
return;
14831511
}

packages/logger/src/config/EnvironmentVariablesService.ts

Lines changed: 0 additions & 126 deletions
This file was deleted.

packages/logger/src/formatter/LogFormatter.ts

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
import type { EnvironmentVariablesService } from '../config/EnvironmentVariablesService.js';
2-
import type { LogFormatterOptions } from '../types/formatters.js';
1+
import {
2+
getStringFromEnv,
3+
isDevMode,
4+
} from '@aws-lambda-powertools/commons/utils/env';
35
import type { LogAttributes } from '../types/Logger.js';
46
import type { UnformattedAttributes } from '../types/logKeys.js';
57
import type { LogItem } from './LogItem.js';
@@ -13,15 +15,6 @@ import type { LogItem } from './LogItem.js';
1315
* @abstract
1416
*/
1517
abstract class LogFormatter {
16-
/**
17-
* Instance of the {@link EnvironmentVariablesService} to use for configuration.
18-
*/
19-
protected envVarsService?: EnvironmentVariablesService;
20-
21-
public constructor(options?: LogFormatterOptions) {
22-
this.envVarsService = options?.envVarsService;
23-
}
24-
2518
/**
2619
* Format key-value pairs of log attributes.
2720
*
@@ -117,9 +110,7 @@ abstract class LogFormatter {
117110
location: this.getCodeLocation(error.stack),
118111
message,
119112
stack:
120-
this.envVarsService?.isDevMode() && typeof stack === 'string'
121-
? stack?.split('\n')
122-
: stack,
113+
isDevMode() && typeof stack === 'string' ? stack?.split('\n') : stack,
123114
cause: cause instanceof Error ? this.formatError(cause) : cause,
124115
};
125116
for (const key in error) {
@@ -137,9 +128,7 @@ abstract class LogFormatter {
137128
/**
138129
* Format a date into an ISO 8601 string with the configured timezone.
139130
*
140-
* If the log formatter is passed an {@link EnvironmentVariablesService} instance
141-
* during construction, the timezone is read from the `TZ` environment variable, if present.
142-
*
131+
* The timezone is read from the `TZ` environment variable, if present.
143132
* Otherwise, the timezone defaults to ':UTC'.
144133
*
145134
* @param now - The date to format
@@ -151,7 +140,11 @@ abstract class LogFormatter {
151140
* If a specific timezone is configured and it's not the default `UTC`,
152141
* format the timestamp with the appropriate timezone offset.
153142
**/
154-
const configuredTimezone = this.envVarsService?.getTimezone();
143+
const configuredTimezone = getStringFromEnv({
144+
key: 'TZ',
145+
defaultValue: '',
146+
});
147+
155148
if (configuredTimezone && !configuredTimezone.includes(defaultTimezone))
156149
return this.#generateISOTimestampWithOffset(now, configuredTimezone);
157150

packages/logger/src/formatter/PowertoolsLogFormatter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class PowertoolsLogFormatter extends LogFormatter {
2727
#logRecordOrder?: LogRecordOrderKeys;
2828

2929
public constructor(options?: PowertoolsLogFormatterOptions) {
30-
super(options);
30+
super();
3131
this.#logRecordOrder = options?.logRecordOrder;
3232
}
3333

0 commit comments

Comments
 (0)