Skip to content

feat: Add release version to lambda conext for logging #4655

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ jobs:
uses: googleapis/release-please-action@a02a34c4d625f9be7cb89156071d8567266a2445 # v4.2.0
with:
target-branch: ${{ steps.branch.outputs.name }}
release-type: terraform-module
manifest-file: .release-please-manifest.json
config-file: .release-please-config.json
token: ${{ steps.token.outputs.token }}
- name: Attest
if: ${{ steps.release.outputs.releases_created == 'true' }}
Expand Down
34 changes: 34 additions & 0 deletions .release-please-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"release-type": "simple",
"packages": {
".": {
"extra-files": [
{
"type": "json",
"path": "lambdas/functions/ami-housekeeper/package.json",
"jsonpath": "$.version"
},
{
"type": "json",
"path": "lambdas/functions/control-plane/package.json",
"jsonpath": "$.version"
},
{
"type": "json",
"path": "lambdas/functions/gh-agent-syncer/package.json",
"jsonpath": "$.version"
},
{
"type": "json",
"path": "lambdas/functions/termination-watcher/package.json",
"jsonpath": "$.version"
},
{
"type": "json",
"path": "lambdas/functions/webhook/package.json",
"jsonpath": "$.version"
}
]
}
}
}
3 changes: 3 additions & 0 deletions .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
".": "6.6.0"
}
18 changes: 18 additions & 0 deletions lambdas/libs/aws-powertools-util/src/logger/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { Context } from 'aws-lambda';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const childLoggers: Logger[] = [];

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const defaultValues = {
region: process.env.AWS_REGION,
environment: process.env.ENVIRONMENT || 'N/A',
};

function getReleaseVersion(): string {
let version = 'unknown';
try {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inention is here to avoid an excetion can crash the lambda.

const packageFilePath = path.resolve(__dirname, 'package.json');
version = JSON.parse(fs.readFileSync(packageFilePath, 'utf-8')).version || 'unknown';
} catch (error) {
logger.debug(`Failed to read package.json for version: ${(error as Error)?.message ?? 'Unknown error'}`);
}
return version;
}

function setContext(context: Context, module?: string) {
logger.addPersistentLogAttributes({
'aws-request-id': context.awsRequestId,
'function-name': context.functionName,
version: getReleaseVersion(),
Comment on lines +25 to +31
Copy link
Preview

Copilot AI Jul 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Calling getReleaseVersion() on every invocation performs synchronous file I/O repeatedly. Consider reading and caching the version once at module load to avoid repeated filesystem access.

Suggested change
}
function setContext(context: Context, module?: string) {
logger.addPersistentLogAttributes({
'aws-request-id': context.awsRequestId,
'function-name': context.functionName,
version: getReleaseVersion(),
})();
function setContext(context: Context, module?: string) {
logger.addPersistentLogAttributes({
'aws-request-id': context.awsRequestId,
'function-name': context.functionName,
version: releaseVersion,

Copilot uses AI. Check for mistakes.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks a good catch, but as far I know the context is only called once via pwoertools.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a fair defensive thing to do,

let releaseVersion: string | null = null;


function setContext(context: Context, module?: string) {
  if (releaseVersion === null) {
    releaseVersion = getReleaseVersion();
  }

  // ...
}

but yeah probably minor, does look like it's only called once per function.

module: module,
});

Expand All @@ -20,6 +37,7 @@ function setContext(context: Context, module?: string) {
childLogger.addPersistentLogAttributes({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't new in this PR so doesn't matter for the review, but it caught my eye... Why do we have to store the child loggers? Should be possible to arrange that only the root logger is ever seen and so we don't need to repeat the attribute addition, right?

'aws-request-id': context.awsRequestId,
'function-name': context.functionName,
version: getReleaseVersion(),
});
});
}
Expand Down
75 changes: 73 additions & 2 deletions lambdas/libs/aws-powertools-util/src/logger/logger.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Context } from 'aws-lambda';
import * as fs from 'fs';
import * as path from 'path';

import { logger, setContext } from '../';
import { describe, test, expect, beforeEach, vi } from 'vitest';
import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest';

beforeEach(() => {
vi.clearAllMocks();
Expand Down Expand Up @@ -29,6 +30,31 @@ const context: Context = {
},
};

const versionFilePath = path.resolve(__dirname, 'package.json');

let logger: typeof import('../').logger;
let setContext: typeof import('../').setContext;

beforeEach(async () => {
// Clear the module cache and reload the logger module
vi.resetModules();
const loggerModule = await import('../');
logger = loggerModule.logger;
setContext = loggerModule.setContext;

// Ensure a clean state before each test
if (fs.existsSync(versionFilePath)) {
fs.unlinkSync(versionFilePath);
}
});

afterEach(() => {
// Clean up after each test
if (fs.existsSync(versionFilePath)) {
fs.unlinkSync(versionFilePath);
}
});
Comment on lines +38 to +56
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be a bit concerned about messing with the real package.json file here, what happens if tests get run in parallel, and the reinitialisaion which seems complex. I would consider doing this with dependency injection. Make getReleaseVersion() take a directory, like this:

function getReleaseVersion(packageDir: string = __dirname): string {
  // ...
}

and then each test could make its own temp dir and set it up how it wants.

It would make sense to still have one integration test which uses the real file under __dirname, to ensure that there's always a version set in there.


describe('A root logger.', () => {
test('Should log set context.', async () => {
setContext(context, 'unit-test');
Expand All @@ -42,3 +68,48 @@ describe('A root logger.', () => {
);
});
});

describe('Logger version handling', () => {
test('Should not fail if package.json does not exist', () => {
// Temporarily rename package.json to simulate its absence
const tempFilePath = `${versionFilePath}.bak`;
if (fs.existsSync(versionFilePath)) {
fs.renameSync(versionFilePath, tempFilePath);
}

setContext(context, 'unit-test');

expect(logger.getPersistentLogAttributes()).toEqual(
expect.objectContaining({
version: 'unknown',
}),
);

// Restore package.json
if (fs.existsSync(tempFilePath)) {
fs.renameSync(tempFilePath, versionFilePath);
}
});

test('Should log version from package.json', () => {
// Create a mock package.json file
const originalPackageData = fs.existsSync(versionFilePath) ? fs.readFileSync(packageFilePath, 'utf-8') : null;
const mockPackageData = JSON.stringify({ version: '1.0.0' });
fs.writeFileSync(versionFilePath, mockPackageData);

setContext(context, 'unit-test');

expect(logger.getPersistentLogAttributes()).toEqual(
expect.objectContaining({
version: '1.0.0',
}),
);

// Restore the original package.json file
if (originalPackageData) {
fs.writeFileSync(versionFilePath, originalPackageData);
} else {
fs.unlinkSync(versionFilePath);
}
});
});