Search code examples
node.jsamazon-ec2amazon-cloudwatchpm2

Best way to set up Node.js logging for app hosted on 2 EC2's with ELB


I have 2 separate but identical instances of an app spinning on two EC2s connected with an Elastic Load Balancer (ELB).

I would like to know the best way you have found to be able to store and retrieve logs from node to troubleshoot issues.

Some users are experimenting authentication/authorization issues and want to put a couple of console.log(usefulStuffToLog)and be able to read it from the AWS console, CloudWatch.


Solution

  • If you configure pm2 to output its logs to a known location on ec2, you can use CloudWatch agent provided by aws to ship the logs to CloudWatch Logs for you.

    Wherever your executing pm2, add either -l or -e and -o switches to specify where to write your pm2 log files:

    -l --log [path]              specify filepath to output both out and error logs
    -o --output <path>           specify out log file
    -e --error <path>            specify error log file
    

    Install CloudWatch agent. Agent can also be used to send instance metrics like available disk space etc. There is a wizard included with CWAgent to help create the json config file which is a good starting point but might require some manual tweaking.

    You need to provide credentials for CWAgent - it can use the instance profile credentials, or you can configure the agent with a APIkey and secret.