client = $client; $this->groupName = $groupName; } protected function write(array $record){ // 1. Determine Stream Name from Context (set in Middleware) $streamName = isset($record['context']['stream']) ? $record['context']['stream'] : _env('CLOUDWATCH_CENTRAL_STREAM', 'centralized-admin-audit-logs'); unset($record['formatted']); // 2. Format the message $message = json_encode($record); // 3. Prepare Log Event $params = [ 'logGroupName' => $this->groupName, 'logStreamName' => $streamName, 'logEvents' => [ [ 'timestamp' => round(microtime(true) * 1000), 'message' => $message ] ] ]; try { $this->client->putLogEvents($params); } catch (CloudWatchLogsException $e) { // Check if error is due to missing Log Stream if ($e->getAwsErrorCode() === 'ResourceNotFoundException') { $this->createStream($streamName); // Retry once try { $this->client->putLogEvents($params); } catch (\Exception $retryException) { // Fallback to local log if retry fails error_log('Audit Log Failed: ' . $retryException->getMessage()); } } } catch (\Exception $e) { // Fail silently or log to default error log to avoid breaking app error_log('Audit Log Integration Error: ' . $e->getMessage()); } } protected function createStream($streamName){ try { $this->client->createLogStream([ 'logGroupName' => $this->groupName, 'logStreamName' => $streamName ]); } catch (\Exception $e) { // Stream might have been created concurrently } } }