Skip to main content

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

EndpointDescription
GET /api/execution-logsAll logs ordered by creation
GET /api/execution/:executionIdLogs 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

  1. Use structured logging: Log objects instead of strings
console.log({ event: 'user_created', userId: user.id, email: user.email });
  1. Include context: Add relevant identifiers
console.log(`[${context.awsRequestId}] Processing user ${userId}`);
  1. Log at appropriate levels:

    • console.log: General information
    • console.info: Important events
    • console.warn: Potential issues
    • console.error: Errors and failures
  2. Don't log sensitive data: Avoid logging passwords, tokens, etc.

Next Steps