@leanstacks/lambda-utils 0.1.0-alpha.3 → 0.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ # Logging Guide
2
+
3
+ This guide explains how to use the Logger utility to implement structured logging in your AWS Lambda functions using TypeScript.
4
+
5
+ ## Overview
6
+
7
+ The Logger utility provides a thin wrapper around [Pino](https://getpino.io/) configured specifically for AWS Lambda. It automatically includes Lambda request context information in your logs and supports multiple output formats suitable for CloudWatch.
8
+
9
+ ## Installation
10
+
11
+ The Logger utility is included in the `@leanstacks/lambda-utils` package:
12
+
13
+ ```bash
14
+ npm install @leanstacks/lambda-utils
15
+ ```
16
+
17
+ ## Quick Start
18
+
19
+ ### Basic Usage
20
+
21
+ ```typescript
22
+ import { Logger } from '@leanstacks/lambda-utils';
23
+
24
+ const logger = new Logger().instance;
25
+
26
+ export const handler = async (event: any, context: any) => {
27
+ logger.info('[Handler] > Processing request');
28
+
29
+ // Your handler logic here
30
+
31
+ logger.info({ key: 'value' }, '[Handler] < Completed request');
32
+
33
+ return { statusCode: 200, body: 'Success' };
34
+ };
35
+ ```
36
+
37
+ ## Configuration
38
+
39
+ The Logger accepts a configuration object to customize its behavior:
40
+
41
+ ```typescript
42
+ import { Logger } from '@leanstacks/lambda-utils';
43
+
44
+ const logger = new Logger({
45
+ enabled: true, // Enable/disable logging (default: true)
46
+ level: 'info', // Minimum log level (default: 'info')
47
+ format: 'json', // Output format: 'json' or 'text' (default: 'json')
48
+ }).instance;
49
+ ```
50
+
51
+ ### Configuration Options
52
+
53
+ | Option | Type | Default | Description |
54
+ | --------- | ---------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
55
+ | `enabled` | `boolean` | `true` | Whether logging is enabled. Set to `false` to disable all logging output. |
56
+ | `level` | `'debug' \| 'info' \| 'warn' \| 'error'` | `'info'` | Minimum log level to output. Messages below this level are filtered out. |
57
+ | `format` | `'json' \| 'text'` | `'json'` | Output format for log messages. Use `'json'` for structured logging or `'text'` for human-readable logs. |
58
+
59
+ ### Log Levels
60
+
61
+ Log levels are ordered by severity:
62
+
63
+ - **`debug`**: Detailed information for diagnosing problems (lowest severity)
64
+ - **`info`**: General informational messages about application flow
65
+ - **`warn`**: Warning messages for potentially harmful situations
66
+ - **`error`**: Error messages for serious problems (highest severity)
67
+
68
+ ## Logging Examples
69
+
70
+ ### Basic Logging
71
+
72
+ ```typescript
73
+ const logger = new Logger().instance;
74
+
75
+ logger.debug('Detailed diagnostic information');
76
+ logger.info('Application event or milestone');
77
+ logger.warn('Warning: something unexpected occurred');
78
+ logger.error('Error: operation failed');
79
+ ```
80
+
81
+ When the log message contains a simple string, pass the string as the only aregument to the logger function.
82
+
83
+ ### Structured Logging with Objects
84
+
85
+ ```typescript
86
+ const logger = new Logger().instance;
87
+
88
+ const userId = '12345';
89
+ const permissions = ['user:read', 'user:write'];
90
+
91
+ logger.info(
92
+ {
93
+ userId,
94
+ permissions,
95
+ },
96
+ 'User authenticated',
97
+ );
98
+ ```
99
+
100
+ When using structured logging, pass the context attributes object as the first parameter and the string log message as the second parameter. This allows the logger to properly format messages as either JSON or text.
101
+
102
+ ### Error Logging
103
+
104
+ ```typescript
105
+ const logger = new Logger().instance;
106
+
107
+ try {
108
+ // Your code here
109
+ } catch (error) {
110
+ logger.error(
111
+ {
112
+ error: error instanceof Error ? error.message : String(error),
113
+ stack: error instanceof Error ? error.stack : undefined,
114
+ },
115
+ 'Operation failed',
116
+ );
117
+ }
118
+ ```
119
+
120
+ ## Advanced Usage
121
+
122
+ ### Request Tracking Middleware
123
+
124
+ The `withRequestTracking` middleware automatically adds AWS Lambda context information to all log messages. This enriches your logs with request IDs, function names, and other Lambda metadata.
125
+
126
+ ```typescript
127
+ import { Logger, withRequestTracking } from '@leanstacks/lambda-utils';
128
+
129
+ const logger = new Logger().instance;
130
+
131
+ export const handler = async (event: any, context: any) => {
132
+ // Add Lambda context to all subsequent log messages
133
+ withRequestTracking(event, context);
134
+
135
+ logger.info('Request started');
136
+
137
+ // Your handler logic here
138
+
139
+ return { statusCode: 200 };
140
+ };
141
+ ```
142
+
143
+ ### Environment-Based Configuration
144
+
145
+ Configure logging based on your environment:
146
+
147
+ ```typescript
148
+ import { Logger } from '@leanstacks/lambda-utils';
149
+
150
+ const isProduction = process.env.NODE_ENV === 'production';
151
+ const isDevelopment = process.env.NODE_ENV === 'development';
152
+
153
+ const logger = new Logger({
154
+ level: isDevelopment ? 'debug' : 'info',
155
+ format: isProduction ? 'json' : 'text',
156
+ }).instance;
157
+ ```
158
+
159
+ ### Singleton Pattern for Reusable Logger
160
+
161
+ For best performance, create a single logger instance and reuse it throughout your application:
162
+
163
+ ```typescript
164
+ // logger.ts
165
+ import { Logger } from '@leanstacks/lambda-utils';
166
+
167
+ export const logger = new Logger({
168
+ level: (process.env.LOG_LEVEL as 'debug' | 'info' | 'warn' | 'error') || 'info',
169
+ format: (process.env.LOG_FORMAT as 'json' | 'text') || 'json',
170
+ }).instance;
171
+ ```
172
+
173
+ Then import it in your handlers:
174
+
175
+ ```typescript
176
+ // handler.ts
177
+ import { logger } from './logger';
178
+
179
+ export const handler = async (event: any) => {
180
+ logger.info({ message: 'Processing event', event });
181
+
182
+ // Your handler logic here
183
+
184
+ return { statusCode: 200 };
185
+ };
186
+ ```
187
+
188
+ ## Best Practices
189
+
190
+ ### 1. Use Structured Logging
191
+
192
+ Prefer objects over string concatenation:
193
+
194
+ ```typescript
195
+ // ✅ Good: Structured logging
196
+ logger.info(
197
+ {
198
+ userId: user.id,
199
+ },
200
+ 'User login',
201
+ );
202
+
203
+ // ❌ Avoid: String concatenation
204
+ logger.info(`User ${user.id} logged in at ${new Date().toISOString()}`);
205
+ ```
206
+
207
+ ### 2. Include Relevant Context
208
+
209
+ Include all relevant information that will help with debugging and monitoring:
210
+
211
+ ```typescript
212
+ logger.info(
213
+ {
214
+ orderId: order.id,
215
+ amount: order.total,
216
+ paymentMethod: order.paymentMethod,
217
+ duration: endTime - startTime,
218
+ },
219
+ 'Payment processed',
220
+ );
221
+ ```
222
+
223
+ ### 3. Use Appropriate Log Levels
224
+
225
+ Choose log levels that match the severity and importance of the event:
226
+
227
+ ```typescript
228
+ logger.debug('Cache hit for user profile'); // Development diagnostics
229
+ logger.info('User registered successfully'); // Normal operations
230
+ logger.warn('API rate limit approaching'); // Potential issues
231
+ logger.error('Database connection failed'); // Critical failures
232
+ ```
233
+
234
+ ### 4. Avoid Logging Sensitive Information
235
+
236
+ Never log passwords, API keys, tokens, or personally identifiable information (PII):
237
+
238
+ ```typescript
239
+ // ❌ Never do this
240
+ logger.info({ password: user.password });
241
+
242
+ // ✅ Log safe information
243
+ logger.info({ userId: user.id, email: user.email });
244
+ ```
245
+
246
+ ### 5. Performance Considerations
247
+
248
+ The logger is optimized for Lambda and uses lazy evaluation. Only use `debug` level logs in development:
249
+
250
+ ```typescript
251
+ // Disable debug logs in production for better performance
252
+ const logger = new Logger({
253
+ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
254
+ }).instance;
255
+ ```
256
+
257
+ ## Output Formats
258
+
259
+ ### JSON Format (Default)
260
+
261
+ Best for production environments and log aggregation services like CloudWatch, Datadog, or Splunk:
262
+
263
+ ```json
264
+ {
265
+ "timestamp": "2025-12-18T13:42:40.502Z",
266
+ "level": "INFO",
267
+ "requestId": "req-abc-123",
268
+ "message": {
269
+ "awsRequestId": "req-def-456",
270
+ "x-correlation-trace-id": "Root=1-2a-28ab;Parent=1e6;Sampled=0;Lineage=1:bf3:0",
271
+ "x-correlation-id": "crl-abc-123",
272
+ "time": 1702900123456,
273
+ "pid": 1,
274
+ "hostname": "lambda-container",
275
+ "key": "value",
276
+ "msg": "User authenticated"
277
+ }
278
+ }
279
+ ```
280
+
281
+ ### Text Format
282
+
283
+ Best for local development and human-readable output:
284
+
285
+ ```
286
+ [2024-12-18T12:34:56.789Z] INFO: User authenticated userId=12345 requestId=req-abc-123
287
+ ```
288
+
289
+ ## Testing
290
+
291
+ When testing Lambda functions that use the logger, you can mock or configure the logger:
292
+
293
+ ```typescript
294
+ import { Logger } from '@leanstacks/lambda-utils';
295
+
296
+ describe('MyHandler', () => {
297
+ it('should log info message', () => {
298
+ const logger = new Logger({
299
+ enabled: true,
300
+ level: 'info',
301
+ }).instance;
302
+
303
+ const spyLog = jest.spyOn(logger, 'info');
304
+
305
+ // Your test code here
306
+
307
+ expect(spyLog).toHaveBeenCalledWith({
308
+ message: 'Expected message',
309
+ });
310
+ });
311
+ });
312
+ ```
313
+
314
+ ## Troubleshooting
315
+
316
+ ### Logs Not Appearing
317
+
318
+ 1. **Check if logging is enabled**: Verify `enabled: true` in configuration
319
+ 2. **Check log level**: Ensure the message log level meets the configured minimum level. Check the Lambda function [Logging configuration application log level](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs-log-level.html).
320
+ 3. **Check CloudWatch**: Logs appear in CloudWatch Logs under `/aws/lambda/[function-name]`
321
+
322
+ ### Performance Issues
323
+
324
+ 1. **Use appropriate log level**: Reduce logs in production by using `level: 'info'`
325
+ 2. **Limit object size**: Avoid logging very large objects that could impact performance
326
+ 3. **Use singleton pattern**: Create one logger instance and reuse it
327
+
328
+ ## Further reading
329
+
330
+ - [Pino Documentation](https://getpino.io/)
331
+ - [AWS Lambda Environment and Context](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html)
332
+ - [CloudWatch Logs Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html)
333
+ - [Back to the project documentation](README.md)
package/docs/README.md CHANGED
@@ -2,47 +2,26 @@
2
2
 
3
3
  Welcome to the Lambda Utilities documentation. This library provides a comprehensive set of utilities and helper functions to streamline the development of AWS Lambda functions using TypeScript.
4
4
 
5
- ## Table of Contents
5
+ ## Overview
6
6
 
7
- - [Getting Started](./GETTING_STARTED.md)
8
- - [Logging](./LOGGING.md)
9
- - [API Gateway Responses](./API_GATEWAY_RESPONSES.md)
10
- - [Configuration](./CONFIGURATION.md)
11
- - [Clients](./CLIENTS.md)
7
+ Lambda Utilities is a collection of pre-configured tools and helpers designed to reduce boilerplate code when developing AWS Lambda functions. It provides utilities for logging, API responses, configuration validation, and AWS SDK client management—all with full TypeScript support.
12
8
 
13
- ## Quick Start
9
+ ## Documentation
14
10
 
15
- Install the package:
16
-
17
- ```bash
18
- npm install @leanstacks/lambda-utils
19
- ```
20
-
21
- Use a utility in your Lambda function:
22
-
23
- ```typescript
24
- import { getLogger } from '@leanstacks/lambda-utils';
25
- import { success } from '@leanstacks/lambda-utils';
26
-
27
- const logger = getLogger();
28
-
29
- export const handler = async (event: any) => {
30
- logger.info({ message: 'Processing event', event });
31
-
32
- // Your handler logic here
33
-
34
- return success({ message: 'Success' });
35
- };
36
- ```
11
+ - **[Logging Guide](./LOGGING.md)** – Implement structured logging in your Lambda functions with Pino and automatic AWS context enrichment
12
+ - **[API Gateway Responses](./API_GATEWAY_RESPONSES.md)** – Format Lambda responses for API Gateway with standard HTTP status codes and headers
13
+ - **[Configuration](./CONFIGURATION.md)** – Validate environment variables and configuration with Zod type safety
14
+ - **[AWS Clients](./CLIENTS.md)** – Pre-configured AWS SDK v3 clients optimized for Lambda
15
+ - **[Getting Started](./GETTING_STARTED.md)** – Quick setup and installation instructions
37
16
 
38
17
  ## Features
39
18
 
40
- - **Logging:** Structured logging with Pino configured for Lambda
41
- - **API Responses:** Standard response formatting for API Gateway
42
- - **Configuration:** Environment variable validation with Zod
43
- - **AWS Clients:** Pre-configured AWS SDK v3 clients
44
- - **Type Safe:** Full TypeScript support with comprehensive types
19
+ - 📝 **Structured Logging** Pino logger pre-configured for Lambda with automatic request context
20
+ - 📤 **API Response Helpers** – Standard response formatting for API Gateway integration
21
+ - ⚙️ **Configuration Validation** – Environment variable validation with Zod schema support
22
+ - 🔌 **AWS Clients** Pre-configured AWS SDK v3 clients for common services
23
+ - 🔒 **Type Safe** Full TypeScript support with comprehensive type definitions
45
24
 
46
25
  ## Support
47
26
 
48
- For issues or questions, please visit the [GitHub repository](https://github.com/leanstacks/lambda-utils).
27
+ For issues or questions, visit the [GitHub repository](https://github.com/leanstacks/lambda-utils).
package/jest.config.ts CHANGED
@@ -3,13 +3,13 @@ import type { Config } from 'jest';
3
3
  const config: Config = {
4
4
  preset: 'ts-jest',
5
5
  testEnvironment: 'node',
6
- rootDir: 'src',
7
- testMatch: ['**/*.test.ts'],
6
+ testMatch: ['<rootDir>/src/**/*.test.ts'],
8
7
  moduleNameMapper: {
9
8
  '^@/(.*)$': '<rootDir>/$1',
10
9
  },
11
- collectCoverageFrom: ['**/*.ts', '!**/*.test.ts'],
12
- coveragePathIgnorePatterns: ['/node_modules/'],
10
+ coverageDirectory: 'coverage',
11
+ collectCoverageFrom: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/index.ts'],
12
+ coverageReporters: ['json', 'json-summary', 'lcov', 'text', 'clover'],
13
13
  };
14
14
 
15
15
  export default config;
package/package.json CHANGED
@@ -1,20 +1,22 @@
1
1
  {
2
2
  "name": "@leanstacks/lambda-utils",
3
- "version": "0.1.0-alpha.3",
3
+ "version": "0.1.0-alpha.5",
4
4
  "description": "A collection of utilities and helper functions designed to streamline the development of AWS Lambda functions using TypeScript.",
5
5
  "main": "dist/index.js",
6
+ "module": "dist/index.esm.js",
6
7
  "types": "dist/index.d.ts",
7
8
  "scripts": {
8
9
  "build": "rollup -c",
9
10
  "build:watch": "rollup -c -w",
10
- "clean": "rimraf dist",
11
- "test": "jest",
12
- "test:watch": "jest --watch",
13
- "test:coverage": "jest --coverage",
11
+ "clean": "rimraf coverage dist",
12
+ "format": "prettier --write \"src/**/*.ts\"",
13
+ "format:check": "prettier --check \"src/**/*.ts\"",
14
14
  "lint": "eslint src",
15
15
  "lint:fix": "eslint src --fix",
16
- "format": "prettier --write \"src/**/*.ts\"",
17
- "format:check": "prettier --check \"src/**/*.ts\""
16
+ "prepare": "husky",
17
+ "test": "jest",
18
+ "test:watch": "jest --watch",
19
+ "test:coverage": "jest --coverage"
18
20
  },
19
21
  "keywords": [
20
22
  "lambda",
@@ -27,16 +29,21 @@
27
29
  "license": "MIT",
28
30
  "devDependencies": {
29
31
  "@eslint/js": "9.39.2",
32
+ "@rollup/plugin-commonjs": "29.0.0",
33
+ "@rollup/plugin-node-resolve": "16.0.3",
34
+ "@rollup/plugin-terser": "0.4.4",
30
35
  "@types/aws-lambda": "8.10.159",
31
36
  "@types/jest": "30.0.0",
32
37
  "@types/node": "25.0.3",
33
38
  "@typescript-eslint/eslint-plugin": "8.50.0",
34
39
  "@typescript-eslint/parser": "8.50.0",
35
40
  "eslint": "9.39.2",
41
+ "husky": "9.1.7",
36
42
  "jest": "30.2.0",
37
43
  "prettier": "3.7.4",
38
44
  "rimraf": "6.1.2",
39
45
  "rollup": "4.53.5",
46
+ "rollup-plugin-peer-deps-external": "2.2.4",
40
47
  "rollup-plugin-typescript2": "0.36.0",
41
48
  "ts-jest": "29.4.6",
42
49
  "ts-node": "10.9.2",
@@ -44,7 +51,6 @@
44
51
  },
45
52
  "dependencies": {
46
53
  "pino": "10.1.0",
47
- "pino-lambda": "4.4.1",
48
- "zod": "4.2.1"
54
+ "pino-lambda": "4.4.1"
49
55
  }
50
56
  }
package/rollup.config.js CHANGED
@@ -1,18 +1,34 @@
1
+ import commonjs from '@rollup/plugin-commonjs';
2
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
3
+ import terser from '@rollup/plugin-terser';
4
+ import peerDepsExternal from 'rollup-plugin-peer-deps-external';
1
5
  import typescript from 'rollup-plugin-typescript2';
2
6
 
7
+ import packageJson from './package.json' with { type: 'json' };
8
+
3
9
  export default {
4
10
  input: 'src/index.ts',
5
11
  output: [
6
12
  {
7
- file: 'dist/index.js',
13
+ file: packageJson.main,
14
+ format: 'cjs',
15
+ sourcemap: true,
16
+ },
17
+ {
18
+ file: packageJson.module,
8
19
  format: 'esm',
20
+ sourcemap: true,
9
21
  },
10
22
  ],
11
- external: ['pino', 'pino-lambda', 'zod', '@aws-sdk/client-dynamodb', '@aws-sdk/client-lambda'],
12
23
  plugins: [
24
+ peerDepsExternal(),
25
+ nodeResolve(),
26
+ commonjs(),
13
27
  typescript({
14
28
  tsconfig: 'tsconfig.json',
15
29
  clean: true,
16
30
  }),
31
+ terser(),
17
32
  ],
33
+ external: [...Object.keys(packageJson.dependencies || {})],
18
34
  };