This project demonstrates how to build and deploy a reusable logging layer for AWS Lambda using TypeScript, AWS CDK, and Node.js Lambda Layers. It includes two Lambda functions (createBlog, getBlogs) that use the shared logging logic via a Lambda Layer.
- Reusable Lambda Layer for logging and error tracking
- Higher-order function wrapper (
withLogger) for structured logs - Type-safe using AWS Lambda types (
APIGatewayProxyEvent, etc.) - CDK-defined infrastructure (Lambdas, Layer, API Gateway)
- Clean, scalable project structure
.
βββ bin/ # CDK app entry point
β βββ aws-lambda-layer-logger.ts
βββ stacks/ # CDK Stack
β βββ aws-lambda-layer-logger-stack.ts
βββ src/
β βββ lambdas/ # Lambda functions
β β βββ createBlog.ts
β β βββ getBlogs.ts
β βββ layers/
β βββ logger/ # Shared logging Layer
β βββ logger.ts
β βββ withLogger.ts
β βββ package.json
β βββ tsconfig.json
βββ package.json
βββ tsconfig.json
βββ cdk.json
npm install
cd src/layers/logger npm install # If using dependencies npm run build # Compile TypeScript to JS (outputs to dist/)
# Run this in the root project directory
cdk deployexport const withLogging = (handler) => async (event, context) => { logger.info("Lambda Invoked", { ... }); try { const result = await handler(event, context); logger.info("Lambda Succeeded", { statusCode: result.statusCode }); return result; } catch (error) { logger.error("Lambda Failed", { error }); throw error; } };
Use it in your handler like:
export const handler = withLogging(async (event) => { ... });
| Method | Path | Lambda | Description |
|---|---|---|---|
| GET | /blog |
getBlogs | Returns a list of blogs |
| POST | /blog |
createBlog | Creates a new blog entry |
Structured logs include context:
{
"level": "info",
"msg": "Lambda Invoked",
"requestId": "abc-123",
"functionName": "CreateBlogFunction",
"path": "/blog",
"httpMethod": "POST"
}- Centralized, DRY logging logic
- Consistent structure across all functions
- Easier debugging and log querying
- Cleaner business logic in handlers