Skip to content

Commit

Permalink
Merge pull request #376 from humanmade/backport-374-to-v5-branch
Browse files Browse the repository at this point in the history
[Backport v5-branch] Truncate SES message data to CloudWatch
  • Loading branch information
roborourke authored Apr 22, 2021
2 parents 8ca2701 + ce45581 commit 3e347d7
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions inc/ses_to_cloudwatch/namespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ function bootstrap() {
* @param array $message The response message.
*/
function on_sent_message( $result, $message ) {
// Truncate the size of message array item to max 5KB.
array_walk_recursive( $message, function ( $value, $key ) {
return truncate_string( $value );
} );

Cloud\get_logger( 'ses', 'Sent' )->info( json_encode( $message ) );
}

Expand All @@ -35,6 +40,11 @@ function on_sent_message( $result, $message ) {
* @param array $message The error message.
*/
function on_error_sending_message( Exception $error, $message ) {
// Truncate the size of message array item to max 5KB.
array_walk_recursive( $message, function ( $value, $key ) {
return truncate_string( $value );
} );

Cloud\get_logger( 'ses', 'Failed' )->error( json_encode( [
'error' => [
'class' => get_class( $error ),
Expand All @@ -43,3 +53,21 @@ function on_error_sending_message( Exception $error, $message ) {
'message' => $message,
] ) );
}

/**
* Truncate string to given maximum size.
*
* @param string $string String to truncate.
* @param int $max_size Maximum size in bytes, default 5KB.
* @param string $replacement String replacement.
*
* @return string
*/
function truncate_string( string $string, int $max_size = 5 * 1024, string $replacement = '' ) : string {
if ( strlen( $string ) < $max_size ) {
return $string;
}

// Truncate string in the middle.
return substr_replace( $string, $replacement, $max_size / 2, strlen( $string ) - $max_size + strlen( $replacement ) );
}

0 comments on commit 3e347d7

Please sign in to comment.