Production-ready Express app with centralized logging to AWS CloudWatch and error tracking with Sentry.
- ✅ Environment-aware logging (dev vs production)
- ✅ Structured JSON logs in CloudWatch
- ✅ Automatic request tracing with unique IDs
- ✅ IAM role-based authentication (no hardcoded keys)
- ✅ Daily log stream rotation
- ✅ Request performance tracking
- ✅ Sentry error tracking and monitoring
npm install
npm startThis runs in development mode with console-only logging.
- Go to AWS CloudWatch Console → Logs → Log groups
- Click Create log group
- Name:
my-app-logs(or your preferred name) - Click Create
- Go to IAM Console → Roles → Create role
- Trusted entity type: AWS service
- Use case: EC2
- Click Next
- Add permissions: Search and select
CloudWatchAgentServerPolicy - Click Next
- Role name:
EC2-CloudWatch-Role(or your preferred name) - Click Create role
- Go to IAM Console → Policies → Create policy
- Click JSON tab
- Paste this policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams"
],
"Resource": "*"
}
]
}- Click Next
- Policy name:
CloudWatchLogsAccess - Click Create policy
- Go to Roles → Create role → EC2 → Attach your new policy → Name it → Create
- Go to EC2 Console → Instances
- Select your instance
- Actions → Security → Modify IAM role
- Select the role created in Step 2 (
EC2-CloudWatch-Role) - Click Update IAM role
SSH into your EC2 instance and create .env file:
cd /path/to/your/app
nano .envAdd these variables:
NODE_ENV=production
AWS_CLOUDWATCH_ENABLED=true
AWS_REGION=us-east-1
AWS_CLOUDWATCH_LOG_GROUP=my-app-logs
PORT=3000Important:
- Replace
us-east-1with your AWS region - Replace
my-app-logswith your log group name - Do NOT add
AWS_ACCESS_KEY_IDorAWS_SECRET_ACCESS_KEY(use IAM role)
# Install dependencies
npm install
# Start the application
npm start
# Generate test logs
curl http://localhost:3000/
curl http://localhost:3000/test/info
curl http://localhost:3000/test/warn
curl http://localhost:3000/test/error
curl http://localhost:3000/test/all
# Test Sentry error tracking
curl http://localhost:3000/debug-sentryWait 30-60 seconds, then check CloudWatch Console. You should see:
- Log group:
my-app-logs - Log stream:
app-YYYY-MM-DD(e.g.,app-2025-10-16) - JSON formatted logs with trace IDs
Add to .env:
SENTRY_DSN=your-sentry-dsn-hereTest: Visit /debug-sentry endpoint to trigger an error.
MIT