デバッグガイド
このガイドでは、ローカル環境とAWS環境の両方でのMBC CQRS Serverlessアプリケーションのデバッグテクニックを説明します。
ローカル開発環境でのデバッグ
NestJS REPLの使用
REPL(Read-Eval-Print Loop)を使用してインタラクティブにデバッグできます:
npm run start:repl
REPLでは以下のことができます:
// Get a service instance (サービスインスタンスを取得)
> get(TodoService)
TodoService { ... }
// Call methods directly (メソッドを直接呼び出す)
> await get(TodoService).findAll()
[{ id: '1', title: 'Test' }, ...]
// Show available methods on a service (サービスで利用可能なメソッドを表示)
> methods(TodoService)
Methods:
◻ findAll
◻ findOne
◻ create
◻ update
◻ delete
NestJS REPLの詳細については、NestJS REPLドキュメントを参照してください。
VS Codeでのデバッグ
.vscode/launch.json 設定を作成します:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Serverless Offline",
"program": "${workspaceFolder}/node_modules/.bin/serverless",
"args": ["offline", "start"],
"cwd": "${workspaceFolder}/infra-local",
"env": {
"NODE_ENV": "development"
},
"console": "integratedTerminal"
},
{
"type": "node",
"request": "launch",
"name": "Debug Tests",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand", "--watchAll=false"],
"console": "integratedTerminal"
}
]
}
Serverless Offlineでのデバッグ
Serverless Offlineで詳細なログを有効にします:
SLS_DEBUG=* npm run offline:sls
またはserverless.ymlに 追加:
custom:
serverless-offline:
httpPort: 3000
lambdaPort: 3002
printOutput: true
コンソールロギング
デバッグを容易にするために構造化ログを使用します:
import { Logger } from '@nestjs/common';
@Injectable()
export class TodoService {
private readonly logger = new Logger(TodoService.name);
async create(dto: CreateTodoDto, invokeContext: IInvoke): Promise<Todo> {
this.logger.debug(`Creating todo: ${JSON.stringify(dto)}`);
try {
const result = await this.commandService.publishAsync(entity, { invokeContext });
this.logger.log(`Todo created: ${result.id}`);
return result;
} catch (error) {
this.logger.error(`Failed to create todo: ${error.message}`, error.stack);
throw error;
}
}
}
DynamoDBのデバッグ
テーブル内容の表示
DynamoDB LocalでAWS CLIを使用:
# List tables
aws dynamodb list-tables --endpoint-url http://localhost:8000
# Scan table
aws dynamodb scan \
--table-name your-table-name \
--endpoint-url http://localhost:8000
# Query by partition key
aws dynamodb query \
--table-name your-table-name \
--key-condition-expression "pk = :pk" \
--expression-attribute-values '{":pk":{"S":"TODO#123"}}' \
--endpoint-url http://localhost:8000
DynamoDB Streams
ストリームレコードをデバッグ:
@EventHandler(DataSyncEvent)
export class DebugHandler implements IEventHandler<DataSyncEvent> {
async execute(event: DataSyncEvent): Promise<void> {
console.log('Stream record:', JSON.stringify(event.record, null, 2));
console.log('Event name:', event.eventName);
console.log('New image:', event.newImage);
console.log('Old image:', event.oldImage);
}
}
CloudWatch Logs
ログの表示
AWS CLIを使用してログをテール:
# Find log group
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/your-app
# Tail logs
aws logs tail /aws/lambda/your-app-dev-handler --follow
# Filter logs
aws logs filter-log-events \
--log-group-name /aws/lambda/your-app-dev-handler \
--filter-pattern "ERROR"
Log Insightsクエリ
高度なクエリにはCloudWatch Logs Insightsを使用:
# Find errors
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 100
# Analyze cold starts
fields @timestamp, @message, @duration
| filter @type = "REPORT"
| stats avg(@duration), max(@duration), count(*) by bin(1h)
# Find slow requests
fields @timestamp, @message, @duration
| filter @duration > 3000
| sort @duration desc
| limit 20
構造化ログ分析
構造化ログを使用している場合:
fields @timestamp, level, message, context
| filter level = "error"
| sort @timestamp desc
Step Functionsのデバッグ
実行履歴
AWSコンソールで実行を表示:
- Step Functions → ステートマシン に移動
- ステートマシンを選択
- 実行をクリック
- ステップステータス付きのビジュアルワークフローを表示