Skip to content

Commit 11af21a

Browse files
dreamorosiijemmy
andauthored
fix(logger): add xray_trace_id to every log (#776)
* fix: add xray_trace_id to logs * chore: 100% test coverage is back * chore: typo in comments * Update docs/core/logger.md Co-authored-by: ijemmy <[email protected]> Co-authored-by: ijemmy <[email protected]>
1 parent af0cefb commit 11af21a

9 files changed

+115
-63
lines changed

Diff for: docs/core/logger.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ Key | Example | Note
100100
**sampling_rate**: `float` | `0.1` | When enabled, it prints all the logs of a percentage of invocations, e.g. 10%
101101
**service**: `string` | `serverlessAirline` | A unique name identifier of the service this Lambda function belongs to, by default `service_undefined`
102102
**timestamp**: `string` | `2011-10-05T14:48:00.000Z` | Timestamp string in simplified extended ISO format (ISO 8601)
103-
**xray_trace_id**: `string` | `1-5759e988-bd862e3fe1be46a994272793` | When [tracing is enabled](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html){target="_blank"}, it shows X-Ray Trace ID
103+
**xray_trace_id**: `string` | `1-5759e988-bd862e3fe1be46a994272793` | X-Ray Trace ID. This value is always presented in Lambda environment, whether [tracing is enabled](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html){target="_blank"} or not. Logger will always log this value.
104104
**error**: `Object` | `{ name: "Error", location: "/my-project/handler.ts:18", message: "Unexpected error #1", stack: "[stacktrace]"}` | Optional - An object containing information about the Error passed to the logger
105105

106106
### Capturing Lambda context info

Diff for: packages/logger/src/Logger.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@ class Logger extends Utility implements ClassThatLogs {
328328
logLevel,
329329
timestamp: new Date(),
330330
message: typeof input === 'string' ? input : input.message,
331+
xRayTraceId: this.getXrayTraceId(),
331332
}, this.getPowertoolLogData());
332333

333334
const logItem = new LogItem({
@@ -428,6 +429,23 @@ class Logger extends Utility implements ClassThatLogs {
428429
return <number> this.powertoolLogData?.sampleRateValue;
429430
}
430431

432+
/**
433+
* It returns the current X-Ray Trace ID parsing the content of the `_X_AMZN_TRACE_ID` env variable.
434+
*
435+
* The X-Ray Trace data available in the environment variable has this format:
436+
* `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`,
437+
*
438+
* The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`.
439+
*
440+
* @private
441+
* @returns {string}
442+
*/
443+
private getXrayTraceId(): string {
444+
const xRayTraceId = this.getEnvVarsService().getXrayTraceId();
445+
446+
return xRayTraceId.length > 0 ? xRayTraceId.split(';')[0].replace('Root=', '') : xRayTraceId;
447+
}
448+
431449
/**
432450
* It returns true if the provided log level is valid.
433451
*
@@ -629,7 +647,6 @@ class Logger extends Utility implements ClassThatLogs {
629647
sampleRateValue: this.getSampleRateValue(),
630648
serviceName:
631649
serviceName || this.getCustomConfigService()?.getServiceName() || this.getEnvVarsService().getServiceName() || Logger.defaultServiceName,
632-
xRayTraceId: this.getEnvVarsService().getXrayTraceId(),
633650
},
634651
persistentLogAttributes,
635652
);

Diff for: packages/logger/tests/e2e/basicFeatures.middy.test.FunctionCode.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,16 @@ const testFunction = async (event: APIGatewayProxyEvent, context: Context): Prom
1818
// Test feature 1: Log level filtering
1919
// Test feature 2: Context data
2020
// Test feature 3: Persistent additional log keys and value
21+
// Test feature 4: X-Ray Trace ID injection
2122
logger.debug('##### This should not appear');
2223
logger.info('This is an INFO log with context and persistent key');
2324

24-
// Test feature 4: One-time additional log keys and values
25+
// Test feature 5: One-time additional log keys and values
2526
logger.info('This is an one-time log with an additional key-value', {
2627
[SINGLE_LOG_ITEM_KEY]: SINGLE_LOG_ITEM_VALUE,
2728
});
2829

29-
// Test feature 5: Logging an error object
30+
// Test feature 6: Logging an error object
3031
try {
3132
throw new Error(ERROR_MSG);
3233
} catch (e) {

Diff for: packages/logger/tests/e2e/basicFeatures.middy.test.ts

+10
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,16 @@ describe(`logger E2E tests basic functionalities (middy) for runtime: ${runtime}
144144
}, TEST_CASE_TIMEOUT);
145145
});
146146

147+
describe('X-Ray Trace ID injection', () => {
148+
it('should inject & parse X-Ray Trace ID into every log', async () => {
149+
const logMessages = invocationLogs[0].getFunctionLogs();
150+
151+
for (const message of logMessages) {
152+
expect(message).toContain('xray_trace_id');
153+
}
154+
}, TEST_CASE_TIMEOUT);
155+
});
156+
147157
describe('One-time additional log keys and values', () => {
148158
it('should log additional keys and value only once', async () => {
149159
const logMessages = invocationLogs[0].getFunctionLogs()

Diff for: packages/logger/tests/helpers/populateEnvironmentVariables.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Reserved variables
2-
process.env._X_AMZN_TRACE_ID = 'abcdef123456abcdef123456abcdef123456';
2+
process.env._X_AMZN_TRACE_ID = 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1';
33
process.env.AWS_LAMBDA_FUNCTION_NAME = 'my-lambda-function';
44
process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '128';
55
process.env.AWS_REGION = 'eu-west-1';

0 commit comments

Comments
 (0)