

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# CloudWatch Amazon-Beispiele mit der AWS SDK für PHP Version 3
<a name="cw-examples"></a>

Amazon CloudWatch (CloudWatch) ist ein Webservice, der Ihre Amazon Web Services Services-Ressourcen und die Anwendungen, auf denen Sie laufen, AWS in Echtzeit überwacht. Sie können CloudWatch damit Metriken sammeln und verfolgen. Dabei handelt es sich um Variablen, die Sie für Ihre Ressourcen und Anwendungen messen können. CloudWatch Alarme senden Benachrichtigungen oder nehmen auf der Grundlage von von Ihnen festgelegter Regeln automatisch Änderungen an den Ressourcen vor, die Sie überwachen.

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

**Topics**
+ [Anmeldeinformationen](#examplecredentials)
+ [Mit CloudWatch Amazon-Alarmen arbeiten](cw-examples-work-with-alarms.md)
+ [Metriken abrufen von CloudWatch](cw-examples-getting-metrics.md)
+ [Veröffentlichen benutzerdefinierter Metriken in Amazon CloudWatch](cw-examples-publishing-custom-metrics.md)
+ [Ereignisse an CloudWatch Amazon-Veranstaltungen senden](cw-examples-sending-events.md)
+ [Alarmaktionen mit CloudWatch Amazon-Alarmen verwenden](cw-examples-using-alarm-actions.md)

# Arbeiten mit CloudWatch Amazon-Alarmen mit AWS SDK für PHP Version 3
<a name="cw-examples-work-with-alarms"></a>

Ein CloudWatch Amazon-Alarm überwacht eine einzelne Metrik über einen von Ihnen angegebenen Zeitraum. Der Alarm führt eine oder mehrere Aktionen durch, basierend auf dem Wert der Metrik im Vergleich zu einem bestimmten Schwellenwert in einer Reihe von Zeiträumen.

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Beschreiben Sie einen Alarm mit [DescribeAlarms](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#describealarms).
+ Erstellen Sie einen Alarm mit [PutMetricAlarm](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricalarm).
+ Löschen Sie einen Alarm mit [DeleteAlarms](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#deletealarms).

Der gesamte Beispielcode für die AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

## Alarme beschreiben
<a name="describe-alarms"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function describeAlarms($cloudWatchClient)
{
    try {
        $result = $cloudWatchClient->describeAlarms();

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'Alarms at the effective URI of ' .
                $result['@metadata']['effectiveUri'] . "\n\n";

            if (isset($result['CompositeAlarms'])) {
                $message .= "Composite alarms:\n";

                foreach ($result['CompositeAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= "No composite alarms found.\n";
            }

            if (isset($result['MetricAlarms'])) {
                $message .= "Metric alarms:\n";

                foreach ($result['MetricAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= 'No metric alarms found.';
            }
        } else {
            $message .= 'No alarms found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function describeTheAlarms()
{
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo describeAlarms($cloudWatchClient);
}

// Uncomment the following line to run this code in an AWS account.
// describeTheAlarms();
```

## Alarm erstellen
<a name="create-an-alarm"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function putMetricAlarm(
    $cloudWatchClient,
    $cloudWatchRegion,
    $alarmName,
    $namespace,
    $metricName,
    $dimensions,
    $statistic,
    $period,
    $comparison,
    $threshold,
    $evaluationPeriods
) {
    try {
        $result = $cloudWatchClient->putMetricAlarm([
            'AlarmName' => $alarmName,
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'Statistic' => $statistic,
            'Period' => $period,
            'ComparisonOperator' => $comparison,
            'Threshold' => $threshold,
            'EvaluationPeriods' => $evaluationPeriods
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully created or updated specified alarm.';
            } else {
                return 'Could not create or update specified alarm.';
            }
        } else {
            return 'Could not create or update specified alarm.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricAlarm()
{
    $alarmName = 'my-ec2-resources';
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $statistic = 'Average';
    $period = 300;
    $comparison = 'GreaterThanThreshold';
    $threshold = 1;
    $evaluationPeriods = 1;

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricAlarm(
        $cloudWatchClient,
        $cloudWatchRegion,
        $alarmName,
        $namespace,
        $metricName,
        $dimensions,
        $statistic,
        $period,
        $comparison,
        $threshold,
        $evaluationPeriods
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricAlarm();
```

## Löschen von Alarmen
<a name="delete-alarms"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function deleteAlarms($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->deleteAlarms([
            'AlarmNames' => $alarmNames
        ]);

        return 'The specified alarms at the following effective URI have ' .
            'been deleted or do not currently exist: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function deleteTheAlarms()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo deleteAlarms($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// deleteTheAlarms();
```

# Metriken von Amazon CloudWatch mit AWS SDK für PHP Version 3 abrufen
<a name="cw-examples-getting-metrics"></a>

Metriken sind Daten über die Leistung Ihrer Systeme. Sie können die detaillierte Überwachung einiger Ressourcen, z. B. Ihrer EC2 Amazon-Instances, oder Ihrer eigenen Anwendungsmetriken aktivieren.

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Metriken auflisten mit [ListMetrics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#listmetrics).
+ Rufen Sie Alarme für eine Metrik ab mit [DescribeAlarmsForMetric](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#describealarmsformetric).
+ Rufen Sie Statistiken für eine angegebene Metrik ab mit [GetMetricStatistics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#getmetricstatistics).

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

## Auflisten von Metriken
<a name="list-metrics"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function listMetrics($cloudWatchClient)
{
    try {
        $result = $cloudWatchClient->listMetrics();

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'For the effective URI at ' .
                $result['@metadata']['effectiveUri'] . ":\n\n";

            if (
                (isset($result['Metrics'])) and
                (count($result['Metrics']) > 0)
            ) {
                $message .= "Metrics found:\n\n";

                foreach ($result['Metrics'] as $metric) {
                    $message .= 'For metric ' . $metric['MetricName'] .
                        ' in namespace ' . $metric['Namespace'] . ":\n";

                    if (
                        (isset($metric['Dimensions'])) and
                        (count($metric['Dimensions']) > 0)
                    ) {
                        $message .= "Dimensions:\n";

                        foreach ($metric['Dimensions'] as $dimension) {
                            $message .= 'Name: ' . $dimension['Name'] .
                                ', Value: ' . $dimension['Value'] . "\n";
                        }

                        $message .= "\n";
                    } else {
                        $message .= "No dimensions.\n\n";
                    }
                }
            } else {
                $message .= 'No metrics found.';
            }
        } else {
            $message .= 'No metrics found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function listTheMetrics()
{
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo listMetrics($cloudWatchClient);
}

// Uncomment the following line to run this code in an AWS account.
// listTheMetrics();
```

## Rufen Sie Alarme für eine Metrik ab
<a name="retrieve-alarms-for-a-metric"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function describeAlarmsForMetric(
    $cloudWatchClient,
    $metricName,
    $namespace,
    $dimensions
) {
    try {
        $result = $cloudWatchClient->describeAlarmsForMetric([
            'MetricName' => $metricName,
            'Namespace' => $namespace,
            'Dimensions' => $dimensions
        ]);

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] . ":\n\n";

            if (
                (isset($result['MetricAlarms'])) and
                (count($result['MetricAlarms']) > 0)
            ) {
                $message .= 'Matching alarms for ' . $metricName . ":\n\n";

                foreach ($result['MetricAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= 'No matching alarms found for ' . $metricName . '.';
            }
        } else {
            $message .= 'No matching alarms found for ' . $metricName . '.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function describeTheAlarmsForMetric()
{
    $metricName = 'BucketSizeBytes';
    $namespace = 'AWS/S3';
    $dimensions = [
        [
            'Name' => 'StorageType',
            'Value' => 'StandardStorage'
        ],
        [
            'Name' => 'BucketName',
            'Value' => 'amzn-s3-demo-bucket'
        ]
    ];

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo describeAlarmsForMetric(
        $cloudWatchClient,
        $metricName,
        $namespace,
        $dimensions
    );
}

// Uncomment the following line to run this code in an AWS account.
// describeTheAlarmsForMetric();
```

## Abrufen von Metrikstatistiken
<a name="get-metric-statistics"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function getMetricStatistics(
    $cloudWatchClient,
    $namespace,
    $metricName,
    $dimensions,
    $startTime,
    $endTime,
    $period,
    $statistics,
    $unit
) {
    try {
        $result = $cloudWatchClient->getMetricStatistics([
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'StartTime' => $startTime,
            'EndTime' => $endTime,
            'Period' => $period,
            'Statistics' => $statistics,
            'Unit' => $unit
        ]);

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'For the effective URI at ' .
                $result['@metadata']['effectiveUri'] . "\n\n";

            if (
                (isset($result['Datapoints'])) and
                (count($result['Datapoints']) > 0)
            ) {
                $message .= "Datapoints found:\n\n";

                foreach ($result['Datapoints'] as $datapoint) {
                    foreach ($datapoint as $key => $value) {
                        $message .= $key . ' = ' . $value . "\n";
                    }

                    $message .= "\n";
                }
            } else {
                $message .= 'No datapoints found.';
            }
        } else {
            $message .= 'No datapoints found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getTheMetricStatistics()
{
    // Average number of Amazon EC2 vCPUs every 5 minutes within
    // the past 3 hours.
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $startTime = strtotime('-3 hours');
    $endTime = strtotime('now');
    $period = 300; // Seconds. (5 minutes = 300 seconds.)
    $statistics = ['Average'];
    $unit = 'None';

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo getMetricStatistics(
        $cloudWatchClient,
        $namespace,
        $metricName,
        $dimensions,
        $startTime,
        $endTime,
        $period,
        $statistics,
        $unit
    );

    // Another example: average number of bytes of standard storage in the
    // specified Amazon S3 bucket each day for the past 3 days.

    /*
    $namespace = 'AWS/S3';
    $metricName = 'BucketSizeBytes';
    $dimensions = [
        [
            'Name' => 'StorageType',
            'Value'=> 'StandardStorage'
        ],
        [
            'Name' => 'BucketName',
            'Value' => 'amzn-s3-demo-bucket'
        ]
    ];
    $startTime = strtotime('-3 days');
    $endTime = strtotime('now');
    $period = 86400; // Seconds. (1 day = 86400 seconds.)
    $statistics = array('Average');
    $unit = 'Bytes';

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo getMetricStatistics($cloudWatchClient, $namespace, $metricName,
    $dimensions, $startTime, $endTime, $period, $statistics, $unit);
    */
}

// Uncomment the following line to run this code in an AWS account.
// getTheMetricStatistics();
```

# Veröffentlichen von benutzerdefinierten Metriken in Amazon CloudWatch mit AWS SDK für PHP Version 3
<a name="cw-examples-publishing-custom-metrics"></a>

Metriken sind Daten über die Leistung Ihrer Systeme. Ein Alarm überwacht eine Metrik über einen bestimmten, von Ihnen festgelegten Zeitraum. Er führt eine oder mehrere Aktionen durch, die vom Wert der Metrik im Vergleich zu einem Schwellenwert in einer Reihe von Zeiträumen abhängt.

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Veröffentlichen Sie metrische Daten mit [PutMetricData](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricdata).
+ Erstellen Sie einen Alarm mit [PutMetricAlarm](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricalarm).

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

## Veröffentlichen Sie metrische Daten
<a name="publish-metric-data"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function putMetricData(
    $cloudWatchClient,
    $cloudWatchRegion,
    $namespace,
    $metricData
) {
    try {
        $result = $cloudWatchClient->putMetricData([
            'Namespace' => $namespace,
            'MetricData' => $metricData
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully published datapoint(s).';
            } else {
                return 'Could not publish datapoint(s).';
            }
        } else {
            return 'Error: Could not publish datapoint(s).';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricData()
{
    $namespace = 'MyNamespace';
    $metricData = [
        [
            'MetricName' => 'MyMetric',
            'Timestamp' => 1589228818, // 11 May 2020, 20:26:58 UTC.
            'Dimensions' => [
                [
                    'Name' => 'MyDimension1',
                    'Value' => 'MyValue1'

                ],
                [
                    'Name' => 'MyDimension2',
                    'Value' => 'MyValue2'
                ]
            ],
            'Unit' => 'Count',
            'Value' => 1
        ]
    ];

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricData(
        $cloudWatchClient,
        $cloudWatchRegion,
        $namespace,
        $metricData
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricData();
```

## Alarm erstellen
<a name="create-an-alarm"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function putMetricAlarm(
    $cloudWatchClient,
    $cloudWatchRegion,
    $alarmName,
    $namespace,
    $metricName,
    $dimensions,
    $statistic,
    $period,
    $comparison,
    $threshold,
    $evaluationPeriods
) {
    try {
        $result = $cloudWatchClient->putMetricAlarm([
            'AlarmName' => $alarmName,
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'Statistic' => $statistic,
            'Period' => $period,
            'ComparisonOperator' => $comparison,
            'Threshold' => $threshold,
            'EvaluationPeriods' => $evaluationPeriods
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully created or updated specified alarm.';
            } else {
                return 'Could not create or update specified alarm.';
            }
        } else {
            return 'Could not create or update specified alarm.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricAlarm()
{
    $alarmName = 'my-ec2-resources';
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $statistic = 'Average';
    $period = 300;
    $comparison = 'GreaterThanThreshold';
    $threshold = 1;
    $evaluationPeriods = 1;

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricAlarm(
        $cloudWatchClient,
        $cloudWatchRegion,
        $alarmName,
        $namespace,
        $metricName,
        $dimensions,
        $statistic,
        $period,
        $comparison,
        $threshold,
        $evaluationPeriods
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricAlarm();
```

# Senden von Ereignissen an Amazon CloudWatch Events mit AWS SDK für PHP Version 3
<a name="cw-examples-sending-events"></a>

CloudWatch Events liefert nahezu in Echtzeit einen Stream von Systemereignissen, die Änderungen an den Ressourcen von Amazon Web Services (AWS) für verschiedene Ziele beschreiben. Mit einfachen Regeln können Sie Ereignisse zuordnen und sie zu einer oder mehreren Zielfunktionen oder Streams umleiten.

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Erstellen Sie eine Regel mit [PutRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#putrule).
+ Fügen Sie einer Regel Ziele hinzu mit [PutTargets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#puttargets).
+ Senden Sie benutzerdefinierte Ereignisse an CloudWatch Ereignisse mithilfe von [PutEvents](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#putevents).

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

## Erstellen einer Regel
<a name="create-a-rule"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putRule([
        'Name' => 'DEMO_EVENT', // REQUIRED
        'RoleArn' => 'IAM_ROLE_ARN',
        'ScheduleExpression' => 'rate(5 minutes)',
        'State' => 'ENABLED',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## Fügen Sie Ziele zu einer Regel hinzu
<a name="add-targets-to-a-rule"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putTargets([
        'Rule' => 'DEMO_EVENT', // REQUIRED
        'Targets' => [ // REQUIRED
            [
                'Arn' => 'LAMBDA_FUNCTION_ARN', // REQUIRED
                'Id' => 'myCloudWatchEventsTarget' // REQUIRED
            ],
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## Benutzerdefinierte Ereignisse senden
<a name="send-custom-events"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putEvents([
        'Entries' => [ // REQUIRED
            [
                'Detail' => '<string>',
                'DetailType' => '<string>',
                'Resources' => ['<string>'],
                'Source' => '<string>',
                'Time' => time()
            ],
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# Verwenden von Alarmaktionen mit CloudWatch Amazon-Alarmen mit AWS SDK für PHP Version 3
<a name="cw-examples-using-alarm-actions"></a>

Verwenden Sie Alarmaktionen, um Alarme zu erstellen, die Ihre EC2 Amazon-Instances automatisch stoppen, beenden, neu starten oder wiederherstellen. Sie können die Aktionen zum Anhalten oder Beenden nutzen, wenn eine Instance nicht mehr ausgeführt werden muss. Sie können die Aktionen zum Neustarten oder Wiederherstellen verwenden, um diese Instances automatisch neu zu starten.

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Aktivieren Sie Aktionen für bestimmte Alarme mithilfe von [EnableAlarmActions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#enablealarmactions).
+ Deaktivieren Sie Aktionen für bestimmte Alarme mit [DisableAlarmActions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#disablealarmactions).

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

## Aktivieren von Alarmaktionen
<a name="enable-alarm-actions"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function enableAlarmActions($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->enableAlarmActions([
            'AlarmNames' => $alarmNames
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            return 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] .
                ', actions for any matching alarms have been enabled.';
        } else {
            return'Actions for some matching alarms ' .
                'might not have been enabled.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function enableTheAlarmActions()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo enableAlarmActions($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// enableTheAlarmActions();
```

## Deaktivieren von Alarmaktionen
<a name="disable-alarm-actions"></a>

 **Importe** 

```
require 'vendor/autoload.php';

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
function disableAlarmActions($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->disableAlarmActions([
            'AlarmNames' => $alarmNames
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            return 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] .
                ', actions for any matching alarms have been disabled.';
        } else {
            return 'Actions for some matching alarms ' .
                'might not have been disabled.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function disableTheAlarmActions()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo disableAlarmActions($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// disableTheAlarmActions();
```