Logging
Learn how to use the logging system in Serverless Monolith for debugging and monitoring.
Execution Logs
Every HTTP request and SQS message has a unique executionId. All logs during that execution are captured and can be retrieved via API.
HTTP Execution ID
The execution ID is returned in the response header:
curl -v http://localhost:4005/api/http/user/users
# Response headers include:
# X-Execution-Id: abc123-def456-...
Retrieving Logs
# Get logs for a specific execution
curl http://localhost:4005/api/execution/abc123-def456
# Get all HTTP execution logs
curl http://localhost:4005/api/http/logs
# Get all SQS execution logs
curl http://localhost:4005/api/sqs/logs
Log Categories
Configure which log categories to enable:
{
logging: {
enabledCategories: [
'adapterStartupInfo', // Server startup information
'httpRequestInfo', // HTTP request details
'httpResponseInfo', // HTTP response details
'sqsMessageInfo', // SQS message processing
'moduleDiscovery', // Module discovery process
'handlerExecution', // Handler execution details
],
showRoutesTable: true,
}
}
Console Logging in Handlers
Use standard console methods in your handlers:
export const handler: APIGatewayProxyHandler = async (event, context) => {
console.log('Processing request:', event.path);
console.info('Request body:', event.body);
console.warn('Deprecated endpoint used');
console.error('Validation failed:', errors);
// Logs are captured with the executionId
return { statusCode: 200, body: '{}' };
};
Debug Package Integration
Logs from the debug package are automatically captured:
import debug from 'debug';
const log = debug('myapp:user');
export const handler: APIGatewayProxyHandler = async (event) => {
log('Creating user with data:', event.body);
// ...
};
Enable debug logs with the DEBUG environment variable:
DEBUG=myapp:* pnpm start
Routes Table
View discovered routes on startup:
{
logging: {
showRoutesTable: true,
routesTableFormat: 'byMethod' // or 'byModule'
}
}
Output example (byMethod):
┌─────────┬──────────────────────┬────────────────────────────┐
│ Method │ Path │ Handler │
├─────────┼──────────────────────┼────────────────────────────┤
│ GET │ /users │ user/handlers/list │
│ GET │ /users/{id} │ user/handlers/get │
│ POST │ /users │ user/handlers/create │
│ PUT │ /users/{id} │ user/handlers/update │
│ DELETE │ /users/{id} │ user/handlers/delete │
└─────────┴──────────────────────┴────────────────────────────┘
Log Storage Adapters
Store logs in external systems:
import { MonolithServer, ILogStorageAdapter } from '@serverless-monolith/core';
class MongoDBLogStorageAdapter implements ILogStorageAdapter {
async save(executionLog: ExecutionLog): Promise<void> {
await this.collection.insertOne(executionLog);
}
async findByExecutionId(id: string): Promise<ExecutionLog | null> {
return this.collection.findOne({ executionId: id });
}
async findAll(): Promise<ExecutionLog[]> {
return this.collection.find().toArray();
}
}
const server = MonolithServer.create('./config.ts');
server.setLogStorageAdapter(new MongoDBLogStorageAdapter());
API Endpoints
| Endpoint | Description |
|---|---|
GET /api/execution-logs | All logs ordered by creation |
GET /api/execution/:executionId | Logs for specific execution |
GET /api/http/logs/:executionId? | HTTP logs |
GET /api/sqs/logs/:executionId? | SQS logs |
Log Format
Execution logs have the following structure:
interface ExecutionLog {
executionId: string;
type: 'http' | 'sqs';
startTime: Date;
endTime?: Date;
duration?: number;
logs: LogEntry[];
request?: {
method: string;
path: string;
headers: Record<string, string>;
body?: any;
};
response?: {
statusCode: number;
body?: any;
};
error?: {
message: string;
stack?: string;
};
}
Best Practices
- Use structured logging: Log objects instead of strings
console.log({ event: 'user_created', userId: user.id, email: user.email });
- Include context: Add relevant identifiers
console.log(`[${context.awsRequestId}] Processing user ${userId}`);
-
Log at appropriate levels:
console.log: General informationconsole.info: Important eventsconsole.warn: Potential issuesconsole.error: Errors and failures
-
Don't log sensitive data: Avoid logging passwords, tokens, etc.
Next Steps
- Examples - Complete examples
- API Reference - Full API documentation