### Minimal Setup Example Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Demonstrates the most basic setup for the CloudWatch handler with minimal configuration. Requires only 3 lines of code. ```php use Monolog\Logger; use Pharos\Monolog\Handler\CloudWatchHandler; $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1')); ``` -------------------------------- ### Production Web Application Setup Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Configuration example for a production web application environment. Includes rate limiting and cache configuration. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'rate' => 1000, 'cache' => [ 'path' => '/tmp/monolog_cache', ], ])); ``` -------------------------------- ### Minimal CloudWatch Handler Example Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md A basic example demonstrating how to set up the CloudWatch handler with Monolog. ```php use Aws\CloudWatchLogs\CloudWatchLogsClient; use Monolog\Logger; use PhpNexus\Cwh\Handler\CloudWatch; $client = new CloudWatchLogsClient([ 'region' => 'us-east-1', 'version' => 'latest' ]); $handler = new CloudWatch($client, 'my-app', 'web-server'); $logger = new Logger('app'); $logger->pushHandler($handler); $logger->info('Application started'); ``` -------------------------------- ### Install with Composer Source: https://github.com/phpnexus/cwh/blob/master/README.md Install the latest version of the library using Composer. ```bash $ composer require phpnexus/cwh:^3.0 ``` -------------------------------- ### Install CloudWatch Handler Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Install the CloudWatch handler using Composer. ```bash composer require phpnexus/cwh:^3.0 ``` -------------------------------- ### Pre-created Resources Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Configuration example demonstrating how to use pre-created AWS resources without enabling auto-creation. This is useful when IAM permissions are restricted. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'auto_create_group' => false, ])); ``` -------------------------------- ### CLI Daemon Setup with Rate Limiting Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Configuration for a long-running CLI daemon, incorporating rate limiting to manage log volume. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'rate' => 500, ])); ``` -------------------------------- ### Type Conversion Example (String to Int) Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Illustrates a type conversion from a string to an integer, a common operation when processing log data. ```php $stringValue = '123'; $intValue = (int) $stringValue; var_dump($intValue); ``` -------------------------------- ### Type Conversion Example (Int to String) Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Shows a type conversion from an integer to a string, useful for formatting log messages or preparing data for output. ```php $intValue = 456; $stringValue = (string) $intValue; var_dump($stringValue); ``` -------------------------------- ### Instantiate and Use CloudWatch Handler Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Example of creating an AWS CloudWatch Logs client, configuring the handler with custom parameters, and pushing it to a Monolog logger. ```php use Aws\CloudWatchLogs\CloudWatchLogsClient; use Monolog\Logger; use Monolog\Level; use PhpNexus\Cwh\Handler\CloudWatch; $client = new CloudWatchLogsClient([ 'region' => 'us-east-1', 'version' => 'latest' ]); $handler = new CloudWatch( $client, 'my-app-logs', 'production-server-1', retention: 30, batchSize: 5000, tags: ['environment' => 'prod', 'service' => 'api'], level: Level::Info ); $logger = new Logger('app'); $logger->pushHandler($handler); $logger->info('Application started'); ``` -------------------------------- ### Constructor Validation Error Example Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Illustrates a constructor validation error, likely due to invalid parameters. This example focuses on the error scenario. ```php try { new CloudWatchHandler(null, 'us-east-1'); } catch (\InvalidArgumentException $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### IAM Permission Policy Example Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt An example of an IAM permission policy required for the CloudWatch handler to send logs to AWS. This JSON defines the necessary permissions. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" } ] } ``` -------------------------------- ### Multiple Streams per Group Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Example showing how to configure the handler to send logs to multiple streams within the same CloudWatch log group. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'stream_name' => 'my_custom_stream_prefix_%Y%m%d%H%M%S', ])); ``` -------------------------------- ### AWS API Error Handling Example Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Demonstrates how to catch and handle potential AWS API errors that may occur during log sending. This example shows a generic catch block. ```php try { // Code that sends logs to CloudWatch $handler->handle($record); } catch (\Aws\Exception\AwsException $e) { // Handle AWS API errors echo 'AWS Error: ' . $e->getMessage(); } ``` -------------------------------- ### Configure Tags for Log Group Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Example of setting tags for a CloudWatch log group. Tags are applied only when the handler creates the log group and are not applicable to existing groups. ```php $tags = [ 'environment' => 'production', 'service' => 'payment-api', 'team' => 'platform', 'cost-center' => 'engineering' ]; $handler = new CloudWatch($client, 'logs', 'stream', tags: $tags); ``` -------------------------------- ### Batch Job Setup for Maximum Throughput Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Configuration optimized for batch job processing to achieve maximum throughput. Focuses on batch size tuning and efficient AWS API calls. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'batch_size' => 10000, ])); ``` -------------------------------- ### High-Traffic Application with Caching Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Setup for high-traffic applications utilizing caching to improve performance and reduce direct AWS calls. ```php $log = new Logger('my_channel'); $log->pushHandler(new CloudWatchHandler('my_log_group', 'us-east-1', [ 'cache' => [ 'path' => '/tmp/monolog_cache', 'ttl' => 3600, ], ])); ``` -------------------------------- ### Configure CloudWatch Handler with Monolog Level Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/types.md Set the minimum log level for the CloudWatch handler. Only messages at or above this level will be logged. Ensure Monolog is installed and configured. ```php use Monolog\Level; use Monolog\Logger; use PhpNexus\Cwh\Handler\CloudWatch; $handler = new CloudWatch( $client, 'my-logs', 'web-server', level: Level::Warning // Only WARNING and above ); $logger = new Logger('app'); $logger->pushHandler($handler); $logger->debug('This is not logged'); // Level 100, below threshold $logger->warning('A warning'); // Level 300, logged to CloudWatch $logger->error('An error occurred'); // Level 400, logged to CloudWatch ``` -------------------------------- ### Integrate Monolog with Custom Processor Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Add a Monolog handler and push custom processors to include extra context, such as a request ID, in all logs. This example demonstrates how to extend Monolog's functionality. ```php use Monolog\Logger; use Monolog\Processor\ProcessorInterface; use Monolog\LogRecord; $logger = new Logger('app'); // Add handler $logger->pushHandler($handler); // Add processors for extra context $logger->pushProcessor(new class implements ProcessorInterface { public function __invoke(LogRecord $record): LogRecord { $record->extra['request_id'] = $_SERVER['HTTP_X_REQUEST_ID'] ?? null; return $record; } }); // Now all logs include request_id $logger->info('Request handled'); ``` -------------------------------- ### Basic Usage of CloudWatch Handler Source: https://github.com/phpnexus/cwh/blob/master/README.md Demonstrates how to instantiate and use the CloudWatch handler with Monolog for sending logs to AWS CloudWatch. Ensure AWS credentials and region are correctly configured. ```php 'eu-west-1', 'version' => 'latest', 'credentials' => [ 'key' => 'your AWS key', 'secret' => 'your AWS secret', 'token' => 'your AWS session token', // token is optional ] ]; // Instantiate AWS SDK CloudWatch Logs Client $client = new CloudWatchLogsClient($sdkParams); // Log group name, will be created if none $groupName = 'php-logtest'; // Log stream name, will be created if none $streamName = 'ec2-instance-1'; // Days to keep logs, 14 by default. Set to `null` to allow indefinite retention. $retentionDays = 30; // Instantiate handler (tags are optional) $handler = new CloudWatch($client, $groupName, $streamName, $retentionDays, 10000, ['my-awesome-tag' => 'tag-value'], Level::Info); // Optionally set the JsonFormatter to be able to access your log messages in a structured way $handler->setFormatter(new JsonFormatter()); // Create a log channel $log = new Logger('name'); // Set handler $log->pushHandler($handler); // Add records to the log $log->debug('Foo'); $log->warning('Bar'); $log->error('Baz'); ``` -------------------------------- ### Pre-create Resources in Non-Development Environments Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md In production environments, pre-create CloudWatch log groups and streams to avoid initialization errors. Set 'createGroup' and 'createStream' to false to enforce the use of existing resources. ```php // Production: use pre-created resources to avoid initialization errors $handler = new CloudWatch( $client, 'production-logs', 'web-server', createGroup: false, // Must exist createStream: false // Must exist ); ``` -------------------------------- ### CloudWatch Class Constructor Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Initializes the CloudWatch handler with necessary AWS client and configuration details. ```APIDOC ## `PhpNexus\Cwh\Handler\CloudWatch` Constructor ### Description Initializes the CloudWatch handler with necessary AWS client and configuration details. ### Parameters - **client** (`CloudWatchLogsClient`) - Required - The AWS CloudWatch Logs client instance. - **group** (`string`) - Required - The CloudWatch log group name. - **stream** (`string`) - Required - The CloudWatch log stream name. - **retention** (`int|null`) - Optional - Days to keep logs (null = indefinite). Defaults to 14. - **batchSize** (`int`) - Optional - Maximum number of log events per batch. Defaults to 10000. - **tags** (`array`) - Optional - Tags to apply to log streams. - **level** (`int|string|Level`) - Optional - The minimum logging level. Defaults to `Level::Debug`. - **bubble** (`bool`) - Optional - Whether the handler should bubble up the stack. Defaults to true. - **createGroup** (`bool`) - Optional - Whether to create the log group if it doesn't exist. Defaults to true. - **createStream** (`bool`) - Optional - Whether to create the log stream if it doesn't exist. Defaults to true. - **rpsLimit** (`int`) - Optional - Requests per second limit (0 = disabled). Defaults to 0. - **cacheItemPool** (`?CacheItemPoolInterface`) - Optional - PSR-6 cache for initialization state. - **cacheItemTtl** (`int`) - Optional - Cache expiration in seconds. Defaults to 300 (5 minutes). ``` -------------------------------- ### CloudWatch Class Constructor and Methods Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Details the constructor parameters and public methods available for direct invocation on the CloudWatch class. ```APIDOC ## CloudWatch Class ### Description Provides functionality for interacting with AWS CloudWatch, including logging and configuration. ### Constructor #### Parameters - **aws_key_id** (string) - Required - AWS access key ID. - **aws_secret_key** (string) - Required - AWS secret access key. - **aws_region** (string) - Required - AWS region to connect to. - **log_group_name** (string) - Required - The CloudWatch log group name. - **log_stream_name** (string) - Required - The CloudWatch log stream name. - **version** (string) - Optional - The AWS SDK client version. - **retries** (integer) - Optional - Number of retries for AWS API calls. - **debug_output** (boolean) - Optional - Enables debug output. - **handler** (object) - Optional - A Monolog handler instance. - **formatter** (object) - Optional - A Monolog formatter instance. - **processors** (array) - Optional - An array of Monolog processors. - **batch_size** (integer) - Optional - The size of batches for sending logs. - **batch_timeout** (integer) - Optional - The timeout in seconds for batch sending. ### Public Methods #### `log(array $record)` ### Description Logs a single record to CloudWatch. ### Method `log` ### Parameters #### Request Body - **record** (array) - Required - The log record to send. #### Response #### Success Response (void) This method does not return a value upon successful execution. #### `logs(array $records)` ### Description Logs multiple records to CloudWatch in a batch. ### Method `logs` ### Parameters #### Request Body - **records** (array) - Required - An array of log records to send. #### Response #### Success Response (void) This method does not return a value upon successful execution. #### `flush()` ### Description Forces the immediate sending of any buffered logs. ### Method `flush` ### Parameters None #### Response #### Success Response (void) This method does not return a value upon successful execution. ``` -------------------------------- ### Production Web Application Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Configure the handler for a production web application, setting log retention and level, and enabling auto-creation of resources. ```php $handler = new CloudWatch( $client, 'production-logs', 'web-server-' . gethostname(), retention: 30, level: Level::Info, createGroup: true, createStream: true ); ``` -------------------------------- ### Instantiate CloudWatchLogsClient Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/types.md Use this to create an instance of the CloudWatchLogsClient from the AWS SDK for PHP. Ensure your AWS credentials and region are correctly configured. ```php use Aws\CloudWatchLogs\CloudWatchLogsClient; $client = new CloudWatchLogsClient([ 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => [ 'key' => 'AKIAIOSFODNN7EXAMPLE', 'secret' => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' ] ]); ``` -------------------------------- ### Get Default CloudWatch Formatter Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Retrieves the default formatter for the CloudWatch handler, which includes channel, level name, message, context, and extra fields. A custom formatter can also be set using setFormatter(). ```php $handler = new CloudWatch($client, 'group', 'stream'); // Get the default formatter $formatter = $handler->getFormatter(); // Or set a custom formatter use Monolog Formatter JsonFormatter; $handler->setFormatter(new JsonFormatter()); // Now log records are formatted as JSON $logger->info('User logged in', ['user_id' => 123]); // Output: {"message":"User logged in","context":{"user_id":123},...} ``` -------------------------------- ### CloudWatch Handler Constructor Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Initializes the CloudWatch handler with AWS client, log group/stream details, and configuration options. ```php public function __construct( CloudWatchLogsClient $client, string $group, string $stream, int|null $retention = 14, int $batchSize = 10000, array $tags = [], int|string|Level $level = Level::Debug, bool $bubble = true, bool $createGroup = true, bool $createStream = true, int $rpsLimit = 0, ?CacheItemPoolInterface $cacheItemPool = null, int $cacheItemTtl = 60 * 5 ) ``` -------------------------------- ### Validate Configuration at Startup Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md Validate CloudWatch handler configuration using a try-catch block during initialization. This prevents runtime errors by catching InvalidArgumentException for invalid settings. ```php use InvalidArgumentException; try { $handler = new CloudWatch( $client, getenv('LOG_GROUP'), getenv('LOG_STREAM'), batchSize: (int)getenv('BATCH_SIZE'), rpsLimit: (int)getenv('RPS_LIMIT') ); } catch (InvalidArgumentException $e) { die('Invalid CloudWatch configuration: ' . $e->getMessage()); } ``` -------------------------------- ### Minimal CloudWatch Handler Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Suitable for development and one-off scripts. It uses default batch size and retention, and automatically creates log group and stream if they don't exist. ```php use Aws\CloudWatchLogs\CloudWatchLogsClient; use PhpNexus\Cwh\Handler\CloudWatch; use Monolog\Logger; $client = new CloudWatchLogsClient([ 'region' => 'us-east-1', 'version' => 'latest' ]); $handler = new CloudWatch($client, 'my-app', 'default-stream'); $logger = new Logger('app'); $logger->pushHandler($handler); ``` -------------------------------- ### Pre-created Resources Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Configure the handler when log group and stream resources are already created in CloudWatch, disabling auto-creation. ```php $handler = new CloudWatch( $client, 'existing-group', 'existing-stream', createGroup: false, createStream: false ); ``` -------------------------------- ### Long-Running CLI Daemon Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Configure the handler for a long-running CLI daemon, optimizing for rate limiting and using a cache for initialization state. ```php $handler = new CloudWatch( $client, 'worker-logs', 'consumer-' . getmypid(), batchSize: 1, rpsLimit: 10, // Important: prevent rate limiting cacheItemPool: $cache, cacheItemTtl: 300 ); ``` -------------------------------- ### Directory Structure for CWH Project Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md This snippet shows the file organization within the CWH project, highlighting the location of API references, type definitions, configuration files, and error catalogs. ```bash output/ ├── README.md (this file) ├── api-reference/ │ └── cloudwatch-handler.md (CloudWatch class API) ├── types.md (Type definitions) ├── configuration.md (Configuration patterns) └── errors.md (Error catalog) ``` -------------------------------- ### Monolog Formatter Customization Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Shows how to customize the Monolog formatter used by the CloudWatch handler. This allows for structured log data. ```php use Monolog\Formatter\JsonFormatter; $log = new Logger('my_channel'); $handler = new CloudWatchHandler('my_log_group', 'us-east-1'); $handler->setFormatter(new JsonFormatter()); $log->pushHandler($handler); ``` -------------------------------- ### Implement Rate Limiting for CloudWatch Logs in PHP Source: https://github.com/phpnexus/cwh/blob/master/README.md Configure the CloudWatch handler with a small batch size and a rate per second limit. This is crucial for long-running CLI daemons or workers to prevent exceeding AWS API rate limits for `putLogEvents`. Adjust `batchSize` and `rpsLimit` based on your application's needs and AWS quotas. ```php 'ap-northeast-1', 'version' => 'latest', 'credentials' => [ 'key' => 'your AWS key', 'secret' => 'your AWS secret', 'token' => 'your AWS session token', // token is optional ] ]; // Instantiate AWS SDK CloudWatch Logs Client $client = new CloudWatchLogsClient($sdkParams); // Log group name, will be created if none $groupName = 'php-logtest'; // Log stream name, will be created if none $streamName = 'cli-worker'; // Instantiate handler $handler = new CloudWatch($client, $groupName, $streamName, batchSize: 1, level: Level::Info, rpsLimit: 100); // Optionally set the JsonFormatter to be able to access your log messages in a structured way $handler->setFormatter(new JsonFormatter()); // Create a log channel $log = new Logger('name'); // Set handler $log->pushHandler($handler); // Add lots of records to the log very quickly $i = 0; do { $log->info('Foo'); } while ($i++ < 500); ``` -------------------------------- ### Monolog Processor Addition Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Demonstrates adding a Monolog processor to the CloudWatch handler. Processors can enrich log records before they are sent. ```php use Monolog\Processor\WebProcessor; $log = new Logger('my_channel'); $handler = new CloudWatchHandler('my_log_group', 'us-east-1'); $handler->pushProcessor(new WebProcessor()); $log->pushHandler($handler); ``` -------------------------------- ### Configure CloudWatch Handler for Batch Jobs Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Optimize for batch jobs by using the maximum batch size for high throughput and setting a minimal log retention period to reduce costs. This configuration aims for efficiency in processing large volumes of logs. ```php $handler = new CloudWatch( $client, 'batch-logs', 'job-' . date('Y-m-d-H-i-s'), batchSize: 10000, // Max batch for throughput retention: 1, // Minimal retention to reduce costs rpsLimit: 0, createGroup: true, createStream: true ); ``` -------------------------------- ### CloudWatchHandler Constructor Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/INDEX.md The CloudWatchHandler class constructor accepts 13 parameters to configure its behavior, including AWS client, log group/stream details, batching, rate limiting, and caching. ```APIDOC ## CloudWatchHandler Constructor ### Description Initializes the CloudWatchHandler with various configuration options to manage log sending to AWS CloudWatch. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **client** (CloudWatchLogsClient) - Required - An instance of the AWS SDK CloudWatchLogsClient. - **group** (string) - Required - The name of the CloudWatch log group. - **stream** (string) - Required - The name of the CloudWatch log stream. - **retention** (int|null) - Optional - The retention period in days for the log group. Null means no retention policy is set. - **batchSize** (int) - Optional - The maximum number of log events to send in a single batch. Defaults to 10,000. - **tags** (array) - Optional - An array of tags to apply to the log group. - **level** (int|string|Level) - Optional - The minimum logging level to handle. Defaults to Monolog's Level::DEBUG. - **bubble** (bool) - Optional - Whether to bubble up the logs to other handlers. Defaults to true. - **createGroup** (bool) - Optional - Whether to automatically create the log group if it does not exist. Defaults to false. - **createStream** (bool) - Optional - Whether to automatically create the log stream if it does not exist. Defaults to false. - **rpsLimit** (int) - Optional - The rate limit in requests per second for sending logs. Defaults to 0 (no limit). - **cacheItemPool** (CacheItemPoolInterface|null) - Optional - A PSR-6 compatible cache pool for caching log entries. Defaults to null. - **cacheItemTtl** (int) - Optional - The Time To Live (TTL) for cached log entries in seconds. Defaults to 60. ``` -------------------------------- ### Configure CloudWatch Handler for Web Applications Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Use this configuration for web applications with short-lived requests. It prioritizes sending logs quickly with small batches and no rate limiting at the handler level. ```php $handler = new CloudWatch( $client, 'web-logs', 'instance', batchSize: 1000, // Small batches, send quickly rpsLimit: 0, // No rate limiting (multiple concurrent requests) createGroup: true, createStream: true ); ``` -------------------------------- ### Multiple CloudWatch Log Streams in Same Group Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Organizes logs by creating multiple streams within a single log group, each with different retention policies. This simplifies organization in the CloudWatch Logs console. ```php $handlers = [ 'api' => new CloudWatch($client, 'prod-logs', 'api-server', retention: 30), 'worker' => new CloudWatch($client, 'prod-logs', 'worker', retention: 7), 'batch' => new CloudWatch($client, 'prod-logs', 'batch-job', retention: 3), ]; $logger = new Logger('app'); $logger->pushHandler($handlers['api']); $workerLogger = new Logger('worker'); $workerLogger->pushHandler($handlers['worker']); ``` -------------------------------- ### CloudWatch Class API Reference Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/_DELIVERY_REPORT.txt Details the public API surface of the CloudWatch class, including its constructor, methods, and constants. ```APIDOC ## CloudWatch Class API Reference ### Description This section details the public API of the `CloudWatch` class, including its constructor, public methods, and constants. ### Constructor - **Parameters**: 13 parameters documented. - **Throws**: All 3 constructor exceptions documented. ### Methods - **`close()`**: Public method fully documented. - **`getFormatter()`**: Public method fully documented. - **`setFormatter()`**: Public method fully documented. ### Constants - **`EVENT_SIZE_LIMIT`**: Public constant documented. - **`TIMESPAN_LIMIT`**: Public constant documented. ### Internal Behavior - Buffering - Rate limiting - Caching - Error recovery ``` -------------------------------- ### Production Web Application CloudWatch Handler Configuration Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Optimized for short-lived HTTP requests with many concurrent connections. It batches up to 5,000 events per request, has a 30-day retention, and tags resources for organization. ```php $handler = new CloudWatch( $client, 'production-logs', 'web-server-' . gethostname(), retention: 30, batchSize: 5000, tags: [ 'environment' => 'production', 'service' => 'api', 'region' => 'us-east-1' ], level: Level::Info, createGroup: true, createStream: true ); ``` -------------------------------- ### Handler Close Behavior and Buffer Flushing Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md Shows the close() method's behavior, which flushes any remaining buffered logs. This method is invoked automatically on script termination or exceptions, or explicitly. If close() fails, buffered logs are lost. ```php public function close(): void { $this->flushBuffer(); // Line 478 } ``` -------------------------------- ### CloudWatch Handler Class Definition Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Defines the CloudWatch handler class, extending Monolog's AbstractProcessingHandler. ```php class CloudWatch extends AbstractProcessingHandler ``` -------------------------------- ### Change Formatter to JsonFormatter Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Customize log output to JSON format for better readability with CloudWatch Insights. Ensure the Monolog JsonFormatter is imported. ```php use Monolog\Formatter\JsonFormatter; $handler = new CloudWatch($client, 'logs', 'stream'); $handler->setFormatter(new JsonFormatter()); // Now logs are JSON, readable by CloudWatch Insights queries $logger->info('User logged in', ['user_id' => 123]); // Output: {"message":"User logged in","context":{"user_id":123},...} ``` -------------------------------- ### Configure CloudWatch Handler with PSR-6 Caching Source: https://github.com/phpnexus/cwh/blob/master/README.md This snippet shows how to instantiate the CloudWatch handler with a PSR-6 cache adapter and set a custom cache TTL. Ensure your cache adapter implements Psr\Cache\CacheItemPoolInterface. ```php 'eu-west-1', 'version' => 'latest', 'credentials' => [ 'key' => 'your AWS key', 'secret' => 'your AWS secret', 'token' => 'your AWS session token', // token is optional ] ]; // Instantiate AWS SDK CloudWatch Logs Client $client = new CloudWatchLogsClient($sdkParams); // Log group name, will be created if none $groupName = 'php-logtest'; // Log stream name, will be created if none $streamName = 'ec2-instance-1'; // Create cache adapter (must implement Psr\Cache\CacheItemPoolInterface) $cacheAdapter = new MyCacheAdapter('test-namespace'); // Set cache TTL of 1 hour (default: 5 minutes) $cacheTtl = 3600; // Instantiate handler $handler = new CloudWatch( $client, $groupName, $streamName, cacheItemPool: $cacheAdapter, cacheItemTtl: $cacheTtl, ); // Optionally set the JsonFormatter to be able to access your log messages in a structured way $handler->setFormatter(new JsonFormatter()); // Create a log channel $log = new Logger('name'); // Set handler $log->pushHandler($handler); // Add records to the log $log->debug('Foo'); $log->warning('Bar'); $log->error('Baz'); ``` -------------------------------- ### CloudWatch Handler Constructor Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Initializes the CloudWatch handler for sending logs to AWS CloudWatch Logs. It allows configuration of log group, stream, retention, batching, and more. ```APIDOC ## CloudWatch Handler Constructor ### Description Initializes the CloudWatch handler for sending logs to AWS CloudWatch Logs. It allows configuration of log group, stream, retention, batching, and more. ### Method `__construct` ### Parameters #### Constructor Parameters - **client** (CloudWatchLogsClient) - Required - AWS SDK CloudWatchLogs client instance - **group** (string) - Required - CloudWatch log group name (1-512 characters, allows a-z, A-Z, 0-9, _, -, /, .) - **stream** (string) - Required - CloudWatch log stream name within the group (1-512 characters, no : or * allowed) - **retention** (int|null) - Optional - Number of days to retain log entries; null allows indefinite retention. Only applied when creating a new log group. Default: 14 - **batchSize** (int) - Optional - Number of log events to queue before sending to CloudWatch (max 10000). Default: 10000 - **tags** (array) - Optional - Key-value tags to apply to the log group when created. Default: [] - **level** (int|string|Level) - Optional - Minimum logging level to trigger handler (from Monolog\Level). Default: Level::Debug - **bubble** (bool) - Optional - Whether handled messages bubble up the stack to other handlers. Default: true - **createGroup** (bool) - Optional - Whether to automatically create the log group if it doesn't exist. Default: true - **createStream** (bool) - Optional - Whether to automatically create the log stream if it doesn't exist. Default: true - **rpsLimit** (int) - Optional - Requests per second rate limit for AWS API calls (0 to disable). Default: 0 - **cacheItemPool** (CacheItemPoolInterface|null) - Optional - PSR-6 cache pool for caching group/stream initialization state. Default: null - **cacheItemTtl** (int) - Optional - Cache time-to-live in seconds for initialization state. Default: 300 ### Throws - **InvalidArgumentException** - batchSize > 10000 - **InvalidArgumentException** - rpsLimit < 0 - **InvalidArgumentException** - cacheItemPool is provided but both createGroup and createStream are false ### Usage Example ```php use Aws\CloudWatchLogs\CloudWatchLogsClient; use Monolog\Logger; use Monolog\Level; use PhpNexus\Cwh\Handler\CloudWatch; $client = new CloudWatchLogsClient([ 'region' => 'us-east-1', 'version' => 'latest' ]); $handler = new CloudWatch( $client, 'my-app-logs', 'production-server-1', retention: 30, batchSize: 5000, tags: ['environment' => 'prod', 'service' => 'api'], level: Level::Info ); $logger = new Logger('app'); $logger->pushHandler($handler); $logger->info('Application started'); ``` ``` -------------------------------- ### CloudWatch Class Public Methods Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Provides methods for interacting with the CloudWatch handler, such as flushing logs and managing formatters. ```APIDOC ## Public Methods ### `close(): void` #### Description Flush buffered logs to CloudWatch. ### `getFormatter(): FormatterInterface` #### Description Get the current formatter. ### `setFormatter(FormatterInterface $formatter): HandlerInterface` #### Description Set a custom formatter (inherited). ``` -------------------------------- ### Set Custom Line Formatter for CloudWatch Handler Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/types.md Configure the handler with a custom LineFormatter to define a specific format for human-readable log entries. This allows for tailored log output. ```php use Monolog\Formatter\JsonFormatter; use Monolog\Formatter\LineFormatter; use PhpNexus\Cwh\Handler\CloudWatch; $handler = new CloudWatch($client, 'logs', 'stream'); // Or use custom line format $handler->setFormatter(new LineFormatter( "[%datetime%] %channel%.%level_name%: %message%\n" )); ``` -------------------------------- ### Catching CreateLogStream Errors in PHP Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md Demonstrates how to catch a CloudWatchLogsException when the CreateLogStream API call fails due to an invalid log stream name. It shows retrying with a valid stream name. ```php use Aws\CloudWatchLogs\Exception\CloudWatchLogsException; try { $handler = new CloudWatch( $client, 'my-logs', 'invalid*stream', // Invalid: contains asterisk createStream: true ); $logger->pushHandler($handler); $logger->info('Message'); // Fails here } catch (CloudWatchLogsException $e) { error_log('CreateLogStream failed: ' . $e->getMessage()); // Retry with valid stream name $validHandler = new CloudWatch( $client, 'my-logs', 'invalid-stream', // Use hyphen instead createStream: true ); $logger->pushHandler($validHandler); } ``` -------------------------------- ### No Automatic Buffering on Unrecoverable Errors Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md Illustrates that if PutLogEvents fails even after retry, the buffer is not re-queued, leading to potential log message loss. The handler is marked as failed, and future logs may not be processed. ```php $this->send($this->buffer); // Fails // Exception propagates // $this->buffer remains in memory (not flushed) // But handler is marked failed, future logs may not be processed ``` -------------------------------- ### Integrate PSR-6 Cache with CloudWatch Handler Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/types.md Utilize a PSR-6 compatible cache pool to store initialization states and reduce redundant AWS API calls. Specify the cache pool and its Time To Live (TTL). ```php use Symfony\Component\Cache\Adapter\RedisAdapter; use PhpNexus\Cwh\Handler\CloudWatch; $redis = \Redis::createConnection('redis://localhost'); $cache = new RedisAdapter($redis); $handler = new CloudWatch( $client, 'my-logs', 'web-server', cacheItemPool: $cache, cacheItemTtl: 3600 // Cache for 1 hour ); ``` -------------------------------- ### getFormatter() Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Returns the default formatter for this handler if none has been explicitly set. The default format includes channel, level name, message, context, and extra fields. ```APIDOC ## getFormatter() ### Description Returns the default formatter for this handler if none has been explicitly set. The default format includes channel, level name, message, context, and extra fields. ### Method `getFormatter(): FormatterInterface` ### Parameters None ### Return Type `Monolog\Formatter\FormatterInterface` (specifically `LineFormatter`) ### Format String `"%channel%: %level_name%: %message% %context% %extra%"` ### Usage Example: ```php $handler = new CloudWatch($client, 'group', 'stream'); // Get the default formatter $formatter = $handler->getFormatter(); // Or set a custom formatter use Monolog\Formatter\JsonFormatter; $handler->setFormatter(new JsonFormatter()); // Now log records are formatted as JSON $logger->info('User logged in', ['user_id' => 123]); // Output: {"message":"User logged in","context":{"user_id":123},...} ``` ``` -------------------------------- ### Full AWS IAM Policy for Automatic Resource Creation Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md This comprehensive JSON policy allows for automatic creation of log groups, streams, and setting retention policies, along with writing log events. It covers all necessary actions for dynamic resource management. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:DescribeLogGroups", "logs:PutRetentionPolicy" ], "Resource": "arn:aws:logs:*:*:log-group:*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:DescribeLogStreams" ], "Resource": "arn:aws:logs:*:*:log-group:my-app:*" }, { "Effect": "Allow", "Action": "logs:PutLogEvents", "Resource": "arn:aws:logs:*:*:log-group:my-app:log-stream:*" } ] } ``` -------------------------------- ### Configure CloudWatch Handler for Long-Running CLI Daemons Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md This configuration is suitable for long-running CLI daemons. It sends logs immediately with a batch size of 1, applies a conservative rate limit, and uses caching to avoid repeated AWS calls. ```php $handler = new CloudWatch( $client, 'worker-logs', 'worker-' . getmypid(), batchSize: 1, // Send immediately rpsLimit: 10, // Stay well below AWS quota cacheItemPool: $cache, // Avoid repeated AWS calls cacheItemTtl: 3600 // Cache for 1 hour ); ``` -------------------------------- ### Catching PutLogEvents Errors in PHP Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/errors.md Illustrates how to catch a CloudWatchLogsException when the PutLogEvents API call fails after retries. It suggests using a fallback handler for lost messages. ```php use Aws\CloudWatchLogs\Exception\CloudWatchLogsException; use Monolog\Logger; $handler = new CloudWatch($client, 'my-logs', 'stream'); $logger = new Logger('app'); $logger->pushHandler($handler); try { $logger->info('This message may be buffered'); $logger->warning('This message may be buffered'); // Handler automatically flushes on close or batch size reached $handler->close(); } catch (CloudWatchLogsException $e) { error_log('PutLogEvents failed after retry: ' . $e->getMessage()); // Log messages are lost at this point // Consider fallback handler $fallback = new StreamHandler('logs/error.log'); $logger->pushHandler($fallback); } ``` -------------------------------- ### Add Processors to Enrich Log Records Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Incorporate Monolog processors to automatically add extra data, such as request IDs and memory usage, to every log record. Implement the ProcessorInterface. ```php use Monolog\Processor\ProcessorInterface; $logger->pushProcessor(new class implements ProcessorInterface { public function __invoke(LogRecord $record): LogRecord { $record->extra['request_id'] = $_SERVER['HTTP_X_REQUEST_ID'] ?? null; $record->extra['memory_usage'] = memory_get_usage(true); return $record; } }); // Now all logs include request_id and memory_usage $logger->info('Request processed'); ``` -------------------------------- ### Set Custom CloudWatch Formatter Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/api-reference/cloudwatch-handler.md Sets a custom formatter for the CloudWatch handler, enabling structured querying in CloudWatch. This method supports method chaining and returns the handler instance. ```php use Monolog Formatter JsonFormatter; $handler = new CloudWatch($client, 'group', 'stream'); $handler->setFormatter(new JsonFormatter()); // Now all logs are formatted as JSON for structured querying in CloudWatch $logger->warning('Disk usage high', ['usage_percent' => 92]); ``` -------------------------------- ### CloudWatchHandler Public Methods Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/INDEX.md The CloudWatchHandler class exposes methods for managing the formatter and closing the handler. ```APIDOC ## Public Methods ### `close()` #### Description Closes the handler and flushes any remaining buffered log events. #### Method `close(): void` ### `getFormatter()` #### Description Gets the current formatter instance. #### Method `getFormatter(): FormatterInterface` ### `setFormatter()` #### Description Sets the formatter for the handler. This method is inherited from the base handler class. #### Method `setFormatter(FormatterInterface $formatter): void` ``` -------------------------------- ### High-Traffic CloudWatch Handler with Caching Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/configuration.md Reduces AWS API calls in high-traffic environments by using a PSR-6 cache. Initialization checks the cache for 1 hour, resulting in zero AWS API calls on a cache hit. ```php use Symfony\Component\Cache\Adapter\RedisAdapter; $redis = \Redis::createConnection('redis://localhost'); $cache = new RedisAdapter($redis, 'cwh-cache'); $handler = new CloudWatch( $client, 'high-traffic-logs', 'web-instance-1', cacheItemPool: $cache, cacheItemTtl: 3600, // 1 hour createGroup: true, createStream: true ); ``` -------------------------------- ### CloudWatch Class Constants Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/README.md Defines constants for limits related to log events and batch times. ```APIDOC ## Constants ### `EVENT_SIZE_LIMIT` - **Value**: `1048550` - **Description**: Max bytes per single event. ### `TIMESPAN_LIMIT` - **Value**: `86400000` - **Description**: Max milliseconds per batch (24 hours). ``` -------------------------------- ### Generate Cache Key from Group Name Source: https://github.com/phpnexus/cwh/blob/master/_autodocs/types.md Generates a cache key string by hashing the group name using CRC32c and prefixing it. Ensures unique cache entries for different groups. ```php // string (group/stream name) → string (cache key) $cacheKey = 'cwh-group-' . hash('crc32c', $this->group); // Example: 'cwh-group-a1b2c3d4' ```