Skip to content

Commit

Permalink
Logs refactoring (#344)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chupocabra authored Sep 30, 2024
1 parent 9fa0421 commit ec0b66c
Show file tree
Hide file tree
Showing 32 changed files with 669 additions and 406 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2024-09-26 4.8.7
* Logs refactoring

## 2024-09-26 4.8.6
* Optimized url-validator

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.8.6
4.8.7
9 changes: 0 additions & 9 deletions resources/pot/retailcrm-es_ES.pot
Original file line number Diff line number Diff line change
Expand Up @@ -274,15 +274,6 @@ msgstr "Presionando el botón «Exportar» puedes descargar a todos los pedidos
msgid "Debug information"
msgstr "Información Debug"

msgid "Debug mode"
msgstr "Modo de depuración"

msgid "Enable debug mode in module"
msgstr "Activar el modo de depuración en el módulo"

msgid "Is required to enable debug mode for advanced logs"
msgstr "Se requiere el modo de depuración para habilitar el registro avanzado de logs"

msgid "Custom fields"
msgstr "Campos personalizados"

Expand Down
9 changes: 0 additions & 9 deletions resources/pot/retailcrm-ru_RU.pot
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,6 @@ msgstr "Вы можете экспортировать все заказы и к
msgid "Debug information"
msgstr "Отладочная информация"

msgid "Debug mode"
msgstr "Режим отладки"

msgid "Enable debug mode in module"
msgstr "Активировать режим отладки в модуле"

msgid "Is required to enable debug mode for advanced logs"
msgstr "Требуется включить режим отладки для расширенного логирования"

msgid "Custom fields"
msgstr "Пользовательские поля"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -738,14 +738,6 @@ public function init_form_fields()
'type' => 'checkbox'
];

$this->form_fields['debug_mode'] = [
'label' => __('Enable debug mode in module', 'retailcrm'),
'title' => __('Debug mode', 'retailcrm'),
'description' => __('Is required to enable debug mode for advanced logs', 'retailcrm'),
'class' => 'checkbox',
'type' => 'checkbox'
];

/**
* Debug information
*/
Expand Down
141 changes: 68 additions & 73 deletions src/include/api/class-wc-retailcrm-proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,32 @@ public function __construct($api_url, $api_key, $corporateEnabled = false)
{
$this->corporateEnabled = $corporateEnabled;

if ( ! class_exists( 'WC_Retailcrm_Client_V5' ) ) {
if (!class_exists('WC_Retailcrm_Client_V5')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('include/api/class-wc-retailcrm-client-v5.php'));
}

$this->retailcrm = new WC_Retailcrm_Client_V5($api_url, $api_key);
}

/**
* getCorporateEnabled
*
* @return bool
*/
public function getCorporateEnabled()
public function getCorporateEnabled(): ?bool
{
return $this->corporateEnabled;
}

private static function reduceErrors($errors)
{
$result = '';

foreach ($errors as $key => $error) {
$result .= " [$key] => $error";
}

return $result;
}

/**
* Response will be omitted in debug logs for those methods
* Response will be omitted in logs for those methods
*
* @return string[]
*/
private function methodsWithoutDebugResponse()
private function methodsWithoutFullLog(): array
{
$methodsList = array('statusesList', 'paymentTypesList', 'deliveryTypesList', 'orderMethodsList');
$methodsList = [
'statusesList',
'paymentTypesList',
'deliveryTypesList',
'orderMethodsList',
'storesList',
];

foreach ($methodsList as $key => $method) {
$method = get_class($this->retailcrm) . '::' . $method;
Expand All @@ -68,74 +58,79 @@ private function methodsWithoutDebugResponse()

public function __call($method, $arguments)
{
$result = '';
$response = null;
$called = sprintf('%s::%s', get_class($this->retailcrm), $method);

try {
WC_Retailcrm_Logger::debug(
$called,
array(empty($arguments) ? '[no params]' : print_r($arguments, true))
);
/** @var \WC_Retailcrm_Response $response */
$response = call_user_func_array(array($this->retailcrm, $method), $arguments);
$response = $this->getResponse($method, $arguments);

if (is_string($response)) {
WC_Retailcrm_Logger::debug($called, array($response));
WC_Retailcrm_Logger::info($method, $response, [], WC_Retailcrm_Logger::RESPONSE);

return $response;
}

if (empty($response)) {
WC_Retailcrm_Logger::add(sprintf("[%s] null (no response whatsoever)", $called));
if (!$response instanceof WC_Retailcrm_Response) {
WC_Retailcrm_Logger::error(
$method,
sprintf("[%s] null (no response whatsoever)", $called),
[],
WC_Retailcrm_Logger::RESPONSE
);

return null;
}

if ($response->isSuccessful()) {
// Don't print long lists in debug logs (errors while calling this will be easy to detect anyway)
// Also don't call useless array_map at all while debug mode is off.
if (retailcrm_is_debug()) {
if (in_array(
$called,
$this->methodsWithoutDebugResponse()
)) {
WC_Retailcrm_Logger::debug($called, array('[request was successful, but response is omitted]'));
} else {
WC_Retailcrm_Logger::debug($called, array($response->getRawResponse()));
}
}

$result = ' Ok';
} else {
$result = sprintf(
$called ." : Error: [HTTP-code %s] %s",
$response->getStatusCode(),
$response->getErrorString()
);
$this->logResponse($response, $method, $called);
} catch (WC_Retailcrm_Exception_Curl|WC_Retailcrm_Exception_Json|InvalidArgumentException $exception) {
WC_Retailcrm_Logger::exception($method, $exception);
}

if (isset($response['errors'])) {
$result .= self::reduceErrors($response['errors']);
}
return $response instanceof WC_Retailcrm_Response ? $response : new WC_Retailcrm_Response(900, '{}');
}

WC_Retailcrm_Logger::debug($called, array($response->getErrorString()));
WC_Retailcrm_Logger::debug($called, array($response->getRawResponse()));
}
private function getResponse($method, $arguments)
{
WC_Retailcrm_Logger::info(
$method,
$arguments === [] ? '[no params]' : '[with params]',
['params' => $arguments],
WC_Retailcrm_Logger::REQUEST
);

return call_user_func_array(array($this->retailcrm, $method), $arguments);
}

WC_Retailcrm_Logger::add(sprintf("[%s] %s", $called, $result));
} catch (WC_Retailcrm_Exception_Curl $exception) {
WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage()));
WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString()));
WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result));
} catch (WC_Retailcrm_Exception_Json $exception) {
WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage()));
WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString()));
WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result));
} catch (InvalidArgumentException $exception) {
WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage()));
WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString()));
WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result));
private function logResponse(WC_Retailcrm_Response $response, $method, $called): void
{
if ($response->isSuccessful()) {
if (in_array($called, $this->methodsWithoutFullLog())) {
WC_Retailcrm_Logger::info(
$method,
'Ok',
['body' => 'request was successful, but response is omitted'],
WC_Retailcrm_Logger::RESPONSE
);
} else {
WC_Retailcrm_Logger::info(
$method,
'Ok',
['body' => json_decode($response->getRawResponse(), true)],
WC_Retailcrm_Logger::RESPONSE
);
}
} else {
WC_Retailcrm_Logger::error(
$method,
sprintf(
"Error: [HTTP-code %s] %s",
$response->getStatusCode(),
$response->getErrorString()
),
['response' => json_decode($response->getRawResponse(), true)],
WC_Retailcrm_Logger::RESPONSE
);
}

return !empty($response) ? $response : new WC_Retailcrm_Response(900, '{}');
}
}
endif;
Loading

0 comments on commit ec0b66c

Please sign in to comment.