Skip to content

Commit

Permalink
PLUG-106: Improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
lighe committed Jun 11, 2024
1 parent 22db05b commit 428ef65
Show file tree
Hide file tree
Showing 19 changed files with 102 additions and 56 deletions.
8 changes: 7 additions & 1 deletion Api/Log/LogService.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,11 @@ public function debug(string $type, $data): LogService;
/**
* @param string|int $prefix
*/
public function prefix($prefix): LogService;
public function addPrefix($prefix): LogService;

/**
* @param string|int $prefix
* @return LogService
*/
public function removePrefix($prefix): LogService;
}
4 changes: 2 additions & 2 deletions Controller/Checkout/Process.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function __construct(
ConfigRepository $configRepository,
TransactionRepository $transactionRepository,
SessionHelper $sessionHelper,
LogRepository $logRepository
LogRepository $logger
) {
$this->orderRepository = $orderRepository;
$this->jsonFactory = $jsonFactory;
Expand All @@ -71,7 +71,7 @@ public function __construct(
$this->paymentSettledService = $paymentSettledService;
$this->paymentFailedService = $paymentFailedService;
$this->sessionHelper = $sessionHelper;
$this->logger = $logRepository->prefix('Process');
$this->logger = $logger->addPrefix('Process');
parent::__construct($context);
}

Expand Down
5 changes: 4 additions & 1 deletion Controller/Checkout/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function __construct(
$this->hppService = $hppService;
$this->transactionRepository = $transactionRepository;
$this->sessionHelper = $sessionHelper;
$this->logger = $logger->prefix('RedirectToHpp');
$this->logger = $logger->addPrefix('RedirectToHpp');
parent::__construct($context);
}

Expand Down Expand Up @@ -97,8 +97,11 @@ public function execute(): ResponseInterface
private function createPaymentAndRedirect(): ResponseInterface
{
$order = $this->checkoutSession->getLastRealOrder();
$this->logger->addPrefix("order {$order->getEntityId()}");

$created = $this->paymentCreationService->createPayment($order);
$url = $this->hppService->getRedirectUrl($created);

$transaction = $this->transactionRepository->getByPaymentUuid($created->getId());
$this->sessionHelper->allowQuoteRestoration($transaction->getQuoteId());

Expand Down
2 changes: 1 addition & 1 deletion Gateway/Command/AuthorizePaymentCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class AuthorizePaymentCommand extends AbstractCommand
*/
public function __construct(OrderRepositoryInterface $orderRepository, LogRepository $logger)
{
parent::__construct($orderRepository, $logger->prefix("AuthorizePaymentCommand"));
parent::__construct($orderRepository, $logger->addPrefix("AuthorizePaymentCommand"));
}

/**
Expand Down
3 changes: 2 additions & 1 deletion Gateway/Command/RefundPaymentCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function __construct(
LogService $logger
) {
$this->refundService = $refundService;
parent::__construct($orderRepository, $logger->prefix("RefundPaymentCommand"));
parent::__construct($orderRepository, $logger->addPrefix("RefundPaymentCommand"));
}

/**
Expand All @@ -44,6 +44,7 @@ public function __construct(
protected function executeCommand(array $subject): void
{
$order = $this->getOrder($subject);
$this->logger->addPrefix($order->getEntityId());
$this->refundService->refund($order, (float) SubjectReader::readAmount($subject));
}
}
6 changes: 3 additions & 3 deletions Model/Transaction/Refund/RefundTransactionRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function __construct(
$this->resource = $resource;
$this->dataFactory = $dataFactory;
$this->collectionFactory = $collectionFactory;
$this->logger = $logger->prefix('RefundTransactionRepository');
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -107,7 +107,7 @@ public function save(RefundTransactionDataInterface $entity): RefundTransactionD
$this->resource->save($entity);
return $entity;
} catch (\Exception $exception) {
$this->logger->error('Save failed', $exception);
$this->logger->error('Could not save refund transaction', $exception);
throw new CouldNotSaveException(__(self::COULD_NOT_SAVE_EXCEPTION, $exception->getMessage()));
}
}
Expand All @@ -124,7 +124,7 @@ private function getByColumn(string $col, $value): RefundTransactionDataInterfac
$transaction = $this->dataFactory->create()->load($value, $col);

if (!$transaction->getEntityId()) {
$this->logger->error('Entity not found', $value);
$this->logger->error('Refund transaction not found', $value);
throw new NoSuchEntityException(__('No record found for %1: %2.', $col, $value));
}

Expand Down
6 changes: 4 additions & 2 deletions Model/Webapi/Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function __construct(
$this->file = $file;
$this->transactionRepository = $transactionRepository;
$this->quoteRepository = $quoteRepository;
$this->logger = $logger->prefix('Webhook');
$this->logger = $logger->addPrefix('Webhook');
}

/**
Expand All @@ -92,13 +92,15 @@ public function __construct(
*/
public function processTransfer()
{
$this->refundFailedService->handle('b0327151-99a4-4e38-85fc-2a6795982b4b', 'foo');

Settings::tlAgent('truelayer-magento/' . $this->configProvider->getExtensionVersion());

$webhook = TrueLayerWebhook::configure()
->useProduction(!$this->configProvider->isSandbox($this->getStoreId()))
->create()
->handler(function (TrueLayerWebhookInterface\EventInterface $event) {
$this->logger->debug('Webhook', $event->getBody());
$this->logger->debug('Body', $event->getBody());
})
->handler(function (TrueLayerWebhookInterface\PaymentSettledEventInterface $event) {
$this->paymentSettledService->handle($event->getPaymentId());
Expand Down
4 changes: 2 additions & 2 deletions Observer/CreditMemoObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class CreditMemoObserver implements ObserverInterface
public function __construct(RefundTransactionRepositoryInterface $refundTransactionRepository, LogService $logger)
{
$this->refundTransactionRepository = $refundTransactionRepository;
$this->logger = $logger->prefix('CreditMemoObserver');
$this->logger = $logger->addPrefix('CreditMemoObserver');
}

/**
Expand Down Expand Up @@ -75,6 +75,6 @@ public function execute(Observer $observer)

$refundTransaction->setCreditMemoId((int)$creditMemo->getEntityId());
$this->refundTransactionRepository->save($refundTransaction);
$this->logger->debug('Refund transaction updated');
$this->logger->debug('Transaction updated');
}
}
2 changes: 1 addition & 1 deletion Observer/OrderPlacedObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __construct(
LogService $logger
) {
$this->orderRepository = $orderRepository;
$this->logger = $logger->prefix('OrderPlacedHandler');
$this->logger = $logger->addPrefix('OrderPlacedHandler');
}

/**
Expand Down
4 changes: 2 additions & 2 deletions Service/Client/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function __construct(
LogService $logger
) {
$this->configProvider = $configProvider;
$this->logger = $logger->prefix('ClientFactory');
$this->logger = $logger;
}

/**
Expand All @@ -46,7 +46,7 @@ public function create(int $storeId = 0, ?array $data = []): ?ClientInterface
try {
return $this->createClient($credentials);
} catch (Exception $e) {
$this->logger->debug('Create Fail', $e->getMessage());
$this->logger->debug('Client Creation Failed', $e->getMessage());
throw $e;
}
}
Expand Down
39 changes: 28 additions & 11 deletions Service/Log/LogService.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LogService implements LogServiceInterface
private ConfigProvider $configProvider;
private Logger $debugLogger;
private Logger $errorLogger;
private string $prefix = '';
private array $prefixes = [];

/**
* @param ConfigProvider $configProvider
Expand Down Expand Up @@ -61,21 +61,42 @@ public function debug(string $type, $data = ''): self
/**
* @inheriDoc
*/
public function prefix(string $prefix): self
public function addPrefix($prefix): self
{
$this->prefix = $prefix;
$this->prefixes[] = $prefix;
return $this;
}

/**
* @param int|string $prefix
* @return $this
*/
public function removePrefix($prefix): LogService
{
foreach ($this->prefixes as $key => $value) {
if ($value ===$prefix) {
unset($this->prefixes[$key]);
return $this;
}
}
return $this;
}

/**
* @param string $type
* @param string $msg
* @param mixed $data
* @return string
*/
private function buildMessage(string $type, $data = ''): string
private function buildMessage(string $msg, $data = ''): string
{
return "$this->prefix: $type: {$this->convertDataToString($data)}";
$parts = $this->prefixes;
$parts[] = $msg;

if ($serialisedData = $this->convertDataToString($data)) {
$parts[] = $serialisedData;
}

return join(' > ', $parts);
}

/**
Expand All @@ -84,10 +105,6 @@ private function buildMessage(string $type, $data = ''): string
*/
private function convertDataToString($data): string
{
if (is_string($data)) {
return $data;
}

if ($data instanceof \Exception) {
return $data->getMessage() . " " . $data->getTraceAsString();
}
Expand All @@ -102,6 +119,6 @@ private function convertDataToString($data): string
}
}

return 'failed to serialize error message';
return "{$data}";
}
}
17 changes: 9 additions & 8 deletions Service/Order/BaseTransactionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,9 @@ abstract class BaseTransactionService

/**
* @param LogService $logger
* @return $this
*/
public function logger(LogService $logger): self
{
public function __construct(LogService $logger) {
$this->logger = $logger;
return $this;
}

/**
Expand All @@ -31,20 +28,22 @@ public function logger(LogService $logger): self
*/
public function execute(Callable $fn): void
{
$this->logger->addPrefix('Transaction')->debug('Start');

$transaction = $this->getTransaction();
$this->validateTransaction($transaction);

if ($transaction->getIsLocked()) {
$this->logger->debug('Aborting, locked transaction');
$this->logger->debug('Aborting, locked');
return;
}

if (!in_array($transaction->getStatus(), ['NULL', null])) {
$this->logger->debug('Aborting, transaction already completed');
$this->logger->debug('Aborting, already completed');
return;
}

$this->logger->debug('Locking transaction');
$this->logger->debug('Locking');
$transaction->setIsLocked(true);
$this->saveTransaction($transaction);

Expand All @@ -58,6 +57,7 @@ public function execute(Callable $fn): void
$transaction->setIsLocked(false);
$this->saveTransaction($transaction);
$this->logger->debug('Unlocked transaction');
$this->logger->removePrefix('Transaction');
}
}

Expand All @@ -76,12 +76,13 @@ protected abstract function saveTransaction(BaseTransactionDataInterface $transa
*/
private function validateTransaction(BaseTransactionDataInterface $transaction): void
{
$this->logger->debug("Transaction", [
$this->logger->debug("Details", [
'transaction id' => $transaction->getEntityId(),
'order id' => $transaction->getOrderId(),
]);

if (!$transaction->getOrderId()) {
$this->logger->error('Transaction with missing order found');
throw new Exception('Transaction with missing order found');
}
}
Expand Down
18 changes: 10 additions & 8 deletions Service/Order/PaymentCreationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function __construct(
$this->transactionRepository = $transactionRepository;
$this->userRepository = $userRepository;
$this->mathRandom = $mathRandom;
$this->logger = $logger->prefix('PaymentCreationService');
$this->logger = $logger;
}

/**
Expand All @@ -71,8 +71,7 @@ public function __construct(
*/
public function createPayment(OrderInterface $order): PaymentCreatedInterface
{
$this->logger->prefix($order->getEntityId());
$this->logger->debug('Start');
$this->logger->addPrefix('PaymentCreationService')->debug('Start');

// Get the TL user id if we recognise the email address
$customerEmail = $order->getBillingAddress()->getEmail() ?: $order->getCustomerEmail();
Expand All @@ -84,7 +83,7 @@ public function createPayment(OrderInterface $order): PaymentCreatedInterface
$this->logger->debug('Create client');

$merchantAccountId = $this->getMerchantAccountId($client, $order);
$this->logger->debug('Found merchant account', $merchantAccountId);
$this->logger->debug('Merchant account', $merchantAccountId);

$paymentConfig = $this->createPaymentConfig($order, $merchantAccountId, $customerEmail, $existingUserId);
$payment = $client->payment()->fill($paymentConfig)->create();
Expand Down Expand Up @@ -113,15 +112,18 @@ public function createPayment(OrderInterface $order): PaymentCreatedInterface
*/
private function createPaymentConfig(OrderInterface $order, string $merchantAccId, string $customerEmail, string $existingUserId = null): array
{
$countries = null;
if ($shippingAddress = $order->getShippingAddress()) {
$countries = [ $shippingAddress->getCountryId() ];
}

$config = [
"amount_in_minor" => AmountHelper::toMinor($order->getBaseGrandTotal()),
"currency" => $order->getBaseCurrencyCode(),
"payment_method" => [
"provider_selection" => [
"filter" => [
"countries" => [
$order->getShippingAddress()->getCountryId()
],
"countries" => $countries,
"release_channel" => "general_availability",
"customer_segments" => $this->configRepository->getBankingProviders(),
"excludes" => [
Expand Down Expand Up @@ -175,7 +177,7 @@ private function getMerchantAccountId(ClientInterface $client, OrderInterface $o
}
}

throw new Exception(__('No merchant account found'));
throw new Exception('No merchant account found');
}

/**
Expand Down
Loading

0 comments on commit 428ef65

Please sign in to comment.