🔊 Add logging to the internal REST service

This commit is contained in:
Philipp Stracker 2025-02-27 13:58:44 +01:00
parent 57ee70acba
commit ffbe9c08d5
No known key found for this signature in database
2 changed files with 44 additions and 1 deletions

View file

@ -318,7 +318,9 @@ return array(
);
},
'settings.service.rest-service' => static function ( ContainerInterface $container ) : InternalRestService {
return new InternalRestService();
return new InternalRestService(
$container->get( 'woocommerce.logger.woocommerce' )
);
},
'settings.service.sanitizer' => static function ( ContainerInterface $container ) : DataSanitizer {
return new DataSanitizer();

View file

@ -10,15 +10,42 @@ declare( strict_types = 1 );
namespace WooCommerce\PayPalCommerce\Settings\Service;
use Throwable;
use Psr\Log\LoggerInterface;
class InternalRestService {
/**
* Logger instance.
*
* In this case, the logger is quite important for debugging, because the main
* functionality of this class cannot be step-debugged using Xdebug: While
* a Xdebug session is active, the remote call to the current server is also
* blocked and will end in a timeout.
*
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* Constructor.
*
* @param LoggerInterface $logger Logger instance.
*/
public function __construct( LoggerInterface $logger ) {
$this->logger = $logger;
}
public function get_data( string $endpoint ) : array {
$token = $this->generate_token( $endpoint );
$rest_url = rest_url( $endpoint );
$response = wp_remote_get(
$this->logger->info( "Calling internal REST endpoint: $rest_url" );
$response = wp_remote_request(
$rest_url,
array(
'method' => 'GET',
'headers' => array(
'X-Internal-Token' => $token,
'Content-Type' => 'application/json',
@ -27,6 +54,8 @@ class InternalRestService {
);
if ( is_wp_error( $response ) ) {
$this->logger->error( 'Internal REST error', array( 'response' => $response ) );
return array();
}
@ -35,13 +64,25 @@ class InternalRestService {
try {
$json = json_decode( $body, true, 512, JSON_THROW_ON_ERROR );
} catch ( Throwable $exception ) {
$this->logger->error(
'Internal REST error: Invalid JSON response',
array(
'error' => $exception->getMessage(),
'response_body' => $body,
)
);
return array();
}
if ( ! $json || empty( $json['success'] ) ) {
$this->logger->error( 'Internal REST error: Invalid response', array( 'json' => $json ) );
return array();
}
$this->logger->info( 'Internal REST success', array( 'data' => $json['data'] ) );
return $json['data'];
}