Boost The Monitoring Of Your PHP Application In 15 Minutes With AWS CloudWatch

Ahmad Masabni
Insider Engineering
7 min readAug 28, 2023

AWS CloudWatch is a powerful monitoring and observability service provided by Amazon Web Services (AWS). It allows you to collect and track metrics, collect and monitor log files, and set alarms. In this article, we will explore how to send metrics from a PHP application to AWS CloudWatch, enabling you to gain valuable insights and monitor the performance of your application.

Amazon CloudWatch

Monitoring the performance and health of a web application is a crucial aspect of ensuring a seamless user experience and proactive issue resolution. As developers, we understand the significance of tracking key metrics to gain insights into the application’s behavior, identify bottlenecks, and optimize its performance. However, as applications scale and become more complex, it becomes increasingly challenging to manually track and analyze all relevant metrics.

This is where AWS CloudWatch comes to the rescue. Let’s explore together how we centralized the monitoring process and gain access to a comprehensive set of tools and features to analyze application metrics in real time.

Configuring AWS CloudWatch for Your Application Metrics

For demonstration purposes, we will use the Laravel framework. Before we can start sending metrics from our application, we need to set up AWS CloudWatch if you haven’t done so already. You can follow these steps:

  1. Log in to the AWS Management Console and navigate to the CloudWatch service.
  2. Create a new namespace for your metrics. This namespace acts as a container for related metrics.
  3. Set up any necessary IAM roles or permissions to allow your application to send data to CloudWatch.
  4. Make note of the AWS region and credentials required to access CloudWatch.

There are two ways you can use to send metrics:
A) Using AWS dependencies for metrics integration
B) Logging metrics to log file and sync it with
AWS from the EC2 instance

A) Installing AWS Dependencies for Metric Integration

To send metrics from your application to CloudWatch, you'll need to install a few dependencies. Follow these steps:

  1. Open your project composer.json file.
  2. Add the following dependencies to the require section:
"require": {
"aws/aws-sdk-php": "^3.0",
"guzzlehttp/guzzle": "^7.0"
}

3. Save the file and run composer update to install the dependencies.

Now that we have CloudWatch set up and the necessary dependencies installed, let's implement the logic to send metrics from our application. Follow these steps:

  1. Create a new class, for example, CloudWatchMetricsto encapsulate the metric-sending logic. This class will handle the interaction with AWS CloudWatch.
use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;

class CloudWatchMetrics
{
private $cloudWatch;

public function __construct()
{
$this->cloudWatch = new CloudWatchClient([
'version' => 'latest',
'region' => 'us-west-2', // Replace with your desired region
'credentials' => [
'key' => 'YOUR_AWS_ACCESS_KEY',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
],
]);
}

public function sendMetric($metricName, $metricValue, $dimensions = [])
{
try {
$this->cloudWatch->putMetricData([
'Namespace' => 'YourNamespace', // Replace with your desired namespace
'MetricData' => [
[
'MetricName' => $metricName,
'Value' => $metricValue,
'Timestamp' => time(),
'Dimensions' => $dimensions,
],
],
]);
} catch (AwsException $e) {
// Handle the exception or log the error
error_log($e->getMessage());
}
}
}

2. Inside the CloudWatchMetrics class, we instantiate the AWS SDK and create a CloudWatch client object with the appropriate configuration. Make sure to replace 'YOUR_AWS_ACCESS_KEY' and 'YOUR_AWS_SECRET_ACCESS_KEY' with your actual AWS access key and secret access key.

3. The sendMetric() method handles sending the metrics. It accepts the metric name, value, and optional dimensions. We use the putMetricData() method of the CloudWatch client object to send the metric data to CloudWatch.

4. You can now use the CloudWatchMetrics class to send metrics from your application. For example, if you want to track the execution time of a specific method, you can add the following code snippet:

$metrics = new CloudWatchMetrics();
$start = microtime(true);
// Your method logic goes here
$executionTime = microtime(true) - $start;
$metrics->sendMetric('ExecutionTime', $executionTime, ['Method' => 'methodName']);

In this example, we measure the execution time of a method by calculating the difference between the start time ($start) and the current time. We then call the sendMetric() method to send the metric named 'ExecutionTime' with the calculated execution time value. The optional dimensions can be used to provide additional context, such as the method name.

B) Logging Metrics To Log File From EC2

In this way configure the AWS CloudWatch Logs agent on an EC2 instance. Of course, you can follow this if you have your application installed on an EC2 instance.

Basically, the idea here is to log the metrics to a normal .log file, and with the help of the CloudWatch Logs agent, the logged metrics will be shown in the AWS CloudWatch dashboard.

  1. First, SSH into your EC2 instance using your preferred way to do it.
  2. Download and install the CloudWatch Logs agent on the EC2 instance by running the following commands:
sudo yum update -y
sudo yum install -y awslogs

3. Open the CloudWatch Logs agent configuration file using a text editor

sudo nano /etc/awslogs/awslogs.conf

4. Configure the log files you want to send to CloudWatch Logs. Add the following lines to the end of the file:

[/var/log/laravel.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/www/storage/logs/laravel.log
log_group_name=/laravel-logs
log_stream_name = {instance_id}

5. Replace /var/log/laravel.log with the path to your application's log file, and modify other options as needed. Then save the file and exit the text editor. One last thing you need to do is restart the CloudWatch Logs agent to apply the configuration changes:

sudo service awslogs restart

Now, you can start seeing metrics under the specified log_group_name in AWS CloudWatch whenever you log something to the log file, for example, you can log metrics like this:

Log::channel('errors-debug')::error('error-message', array_merge(
['id' => $someId],
$errors,
['errorDetail' => $lastErrorReason]
));

P.S. Don’t forget to give the necessary permissions for the EC2 instance to send logs to CloudWatch using IAM Policy.

Making the Most of AWS CloudWatch Monitoring

Once your application is sending metrics to CloudWatch, you can leverage the powerful visualization and monitoring capabilities offered by CloudWatch.

Let’s create a metric filter to monitor events in a log group as they are sent to CloudWatch Logs:

  1. Navigate to the Log Groups tab, select the log group name to which you sent the metrics, and click on Create metric filter.
CloudWatch Log Groups

2. In the filter pattern you can define the term that will match your log to be included in this metric, for this example we will select the Error pattern which means whenever this word exists in the log message then it will be captured in this metric

New Filter Pattern Creation

3. Define the filter metric name and namespace that you already have (if not, AWS can create one for you in this step) and we will set the metric value for our case to be 1 because it represents errors count.

4. Select the metric once you create it and click on “Create alarm”.

Created Metric Filter

5. Configure the alarm that we want which in our case it will look something like this, where the sum of this metric shall be greater than 0 in order for this alarm to be triggered, and we selected an SNS topic where it sends a message to a slack channel so that we get notified.

Alarm Configuration

Once the alarm is configured, it will notify you about the metric whenever the threshold is breached.

You can also create custom dashboards to visualize your metrics and gain insights into the performance and health of your application.

Alarms Metrics

Conclusion

As you can see, by sending metrics from your application to AWS CloudWatch, you can gain many benefits such as:

  1. Real-time Monitoring.
  2. Improved Troubleshooting.
  3. Automated Alarms and Notifications.
  4. Scalability and Capacity Planning.
  5. Data-Driven Decision Making.

Remember to continually monitor and adjust your metrics to align with your application's specific requirements. AWS CloudWatch offers a powerful suite of features to help you make data-driven decisions and improve the overall user experience of your application.

If you want to know whether your product load is working correctly, take a look at this article for Logging, monitoring, and alerting with CloudWatch Events, and don’t forget to follow us on Insider Engineering Blog to read more about our Agile Best Practices, AWS solutions at scale, and engineering stories.

--

--