2
votes

I am working on a Laravel project. I am integrating my project with AWS CloudWatch. I am sending custom metric from my application to the AWS CloudWatch. But the problem is that it keeps creating new Metric instead of updating the existing one if the metric already exists.

This is my code.

$client = \Aws\CloudWatch\CloudWatchClient::factory([
        'credentials' => [
            'key' => env('CLOUDWATCH_LOG_KEY', ''),
            'secret' => env('CLOUDWATCH_LOG_SECRET', ''),
        ],
        'region' => env('CLOUDWATCH_LOG_REGION', ''),
        'version' => env('CLOUDWATCH_LOG_VERSION', '')
    ]);

    try {
        $result = $client->putMetricData([
            'Namespace' => 'LaravelAwsOnlineUsersProd',
            'MetricData' => [
                [
                    'MetricName' => 'ConnectedUsers',
                    'Timestamp' => time(),
                    'Value' => 1,
                    'Unit' => 'Kilobytes',
                    'Dimensions' => [
                        [
                            'Name' => 'OnlineUser',
                            'Value' => $connectedUsers
                        ]
                    ]
                ]
            ]
        ]);
        
        //the rest of the code
    } catch (\Aws\Exception\AwsException $e) {
        return $e->getMessage();
    }

I could publish or send the metric to the CloudWatch. The problem is that each time, I send the metric, it creates a new one adding new row instead of updating the existing one as follows:

enter image description here

How can I solve the problem?

The reason I want this is that I am creating a CloudWatch alarm. Then I will have to select the metric dimensions.

enter image description here

If the new data comes in as a new metric, it will not be included in the Alarm.

1

1 Answers

0
votes

Looks like you're trying to count the number of selected users, is that right?

Set the $connectedUsers to the value of the MetricData, not the dimension. Dimension is used to separate the metrics by some criteria.

For example, if you wanted to count the users for each server, you would have a ServerId dimension.

Also, remove the unit, doesn't make sense to count the users in kilobytes.

Try something like this and see if it works for you:

$result = $client->putMetricData([
            'Namespace' => 'LaravelAwsOnlineUsersProd',
            'MetricData' => [
                [
                    'MetricName' => 'ConnectedUsers',
                    'Timestamp' => time(),
                    'Value' => $connectedUsers
                ]
            ]
        ]);

More info on CloudWatch Dimensions: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension