Serverless Logging — Logging Patterns for Serverless Applications
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Serverless Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Serverless logging must account for ephemeral execution environments, cold starts, and asynchronous invocation patterns.
// AWS Lambda structured logger
class LambdaLogger {
constructor() {
this.context = {};
this.coldStart = true;
}
initialize(context) {
this.context = {
functionName: context.functionName,
functionVersion: context.functionVersion,
awsRequestId: context.awsRequestId,
invokedFunctionArn: context.invokedFunctionArn,
memoryLimit: context.memoryLimitInMB,
coldStart: this.coldStart,
logGroup: context.logGroupName,
logStream: context.logStreamName,
timestamp: new Date().toISOString()
};
this.coldStart = false;
}
log(level, message, data = {}) {
const entry = {
...this.context,
level: level.toUpperCase(),
message,
data,
timestamp: new Date().toISOString()
};
// Include cold start marker
if (this.context.coldStart) {
entry.cold_start = true;
}
console.log(JSON.stringify(entry));
}
info(message, data) { this.log('info', message, data); }
error(message, err, data) {
this.log('error', message, {
...data,
error: {
name: err?.name,
message: err?.message,
stack: err?.stack?.split('\n').slice(0, 5)
}
});
}
}
// Lambda handler with logging
const logger = new LambdaLogger();
module.exports.handler = async (event, context) => {
logger.initialize(context);
logger.info('Function invoked', {
source: event.source,
detailType: event['detail-type'],
rawEvent: JSON.stringify(event).slice(0, 500)
});
try {
const result = await processEvent(event);
logger.info('Function completed', { result: JSON.stringify(result).slice(0, 200) });
return result;
} catch (err) {
logger.error('Function failed', err);
throw err;
}
};
// CloudWatch log subscription for aggregation
// Subscription filter -> Lambda -> Elasticsearch
Serverless logging requires structured output to CloudWatch with sufficient context for debugging ephemeral invocations.
← Previous
Logging Best Practices — Comprehensive Guide to Production Logging
Next →
Logging for Debugging — Using Logs Effectively for Root Cause Analysis
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro