Does anyone know how to log all request and responses with the builtin SoapClient in PHP? I could in fact manually log everything with SoapClient::__getLastRequest()>
Adressing the issue raised in https://stackoverflow.com/a/3939077/861788 I came with the following solution (full source):
*/
class LoggingSoapClient
{
const REQUEST = 'Request';
const RESPONSE = 'Response';
/**
* @var TraceableSoapClient
*/
private $soapClient;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @param TraceableSoapClient $soapClient
* @param LoggerInterface $logger
*/
public function __construct(TraceableSoapClient $soapClient, LoggerInterface $logger)
{
$this->soapClient = $soapClient;
$this->logger = $logger;
}
/**
* @param string $method
* @param array $arguments
* @return string
*/
public function __call($method, array $arguments)
{
$result = call_user_func_array([$this->soapClient, $method], $arguments);
if (!method_exists($this->soapClient, $method) || $method === '__soapCall') {
$this->logger->info($this->soapClient->__getLastRequest(), ['type' => self::REQUEST]);
$this->logger->info($this->soapClient->__getLastResponse(), ['type' => self::RESPONSE]);
}
return $result;
}
/**
* @param string $request
* @param string $location
* @param string $action
* @param int $version
* @param int $oneWay
* @return string
*/
public function __doRequest($request, $location, $action, $version, $oneWay = 0)
{
$response = $this->soapClient->__doRequest($request, $location, $action, $version, $oneWay);
$this->logger->info($request, ['type' => self::REQUEST]);
$this->logger->info($response, ['type' => self::RESPONSE]);
return $response;
}
}
Usage:
use Lc5\Toolbox\LoggingSoapClient\LoggingSoapClient;
use Lc5\Toolbox\LoggingSoapClient\TraceableSoapClient;
use Lc5\Toolbox\LoggingSoapClient\MessageXmlFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
$handler = new StreamHandler('path/to/your.log');
$handler->setFormatter(new MessageXmlFormatter());
$logger = new Logger('soap');
$logger->pushHandler($handler);
$soapClient = new LoggingSoapClient(new TraceableSoapClient('http://example.com'), $logger);
SOAP client will then log every request and response using any PSR-3 logger.