Skip to content

Commit

Permalink
Merge pull request #55 from VincentBean/develop
Browse files Browse the repository at this point in the history
#52 Add LogRocket and #53 improve error message
  • Loading branch information
indykoning authored Jun 29, 2020
2 parents a76378f + a76d14f commit ee48126
Show file tree
Hide file tree
Showing 9 changed files with 230 additions and 22 deletions.
34 changes: 32 additions & 2 deletions Block/SentryScript.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public function __construct(
public function canUseScriptTag($blockName)
{
return $this->dataHelper->isActive() &&
$this->dataHelper->useScriptTag() &&
$this->dataHelper->showScriptTagInThisBlock($blockName);
$this->dataHelper->useScriptTag() &&
$this->dataHelper->showScriptTagInThisBlock($blockName);
}

/**
Expand All @@ -47,4 +47,34 @@ public function getDSN()
{
return $this->dataHelper->getDSN();
}

/**
* If LogRocket should be used.
*
* @return bool
*/
public function useLogRocket()
{
return $this->dataHelper->useLogrocket();
}

/**
* If LogRocket identify should be used.
*
* @return bool
*/
public function useLogRocketIdentify()
{
return $this->dataHelper->useLogrocketIdentify();
}

/**
* Gets the LogRocket key.
*
* @return string
*/
public function getLogrocketKey()
{
return $this->dataHelper->getLogrocketKey();
}
}
6 changes: 4 additions & 2 deletions Controller/Adminhtml/Test/Sentry.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ public function execute()
{
$result = ['status' => false];

if ($this->helperSentry->isActive()) {
$activeWithReason = $this->helperSentry->isActiveWithReason();

if ($activeWithReason['active']) {
try {
$this->monologPlugin->addAlert('TEST message from Magento 2', []);
$result['status'] = true;
Expand All @@ -94,7 +96,7 @@ public function execute()
$this->logger->critical($e);
}
} else {
$result['content'] = __('Sentry Domain not filled!');
$result['content'] = implode(PHP_EOL, $activeWithReason['reasons']);
}

return $this->getResponse()->representJson(
Expand Down
62 changes: 57 additions & 5 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Data extends AbstractHelper
*/
protected $configKeys = [
'dsn',
'logrocket_key',
'log_level',
'mage_mode_development',
'environment',
Expand Down Expand Up @@ -125,11 +126,36 @@ public function collectModuleConfig()
*/
public function isActive()
{
return !empty($this->config)
&& array_key_exists('enabled', $this->config)
&& $this->config['enabled']
&& $this->getDSN()
&& ($this->isProductionMode() || $this->isOverwriteProductionMode());
return $this->isActiveWithReason()['active'];
}

/**
* @param string $reason : Reason to tell the user why it's not active (Github issue #53)
*
* @return bool
*/
public function isActiveWithReason()
{
$reasons = [];
$emptyConfig = empty($this->config);
$configEnabled = array_key_exists('enabled', $this->config) && $this->config['enabled'];
$dsnNotEmpty = $this->getDSN();
$productionMode = ($this->isProductionMode() || $this->isOverwriteProductionMode());

if ($emptyConfig) {
$reasons[] = __('Config is empty.');
}
if (!$configEnabled) {
$reasons[] = __('Module is not enabled in config.');
}
if (!$dsnNotEmpty) {
$reasons[] = __('DSN is empty.');
}
if (!$productionMode) {
$reasons[] = __('Not in production and development mode is false.');
}

return count($reasons) > 0 ? ['active' => false, 'reasons' => $reasons] : ['active' => true];
}

/**
Expand Down Expand Up @@ -198,4 +224,30 @@ public function showScriptTagInThisBlock($blockName)

return $name == $blockName;
}

/**
* @return mixed
*/
public function getLogrocketKey()
{
return $this->config['logrocket_key'];
}

/**
* @return bool
*/
public function useLogrocket()
{
return $this->scopeConfig->isSetFlag(static::XML_PATH_SRS.'use_logrocket') &&
array_key_exists('logrocket_key', $this->config) &&
$this->config['logrocket_key'] != null;
}

/**
* @return bool
*/
public function useLogrocketIdentify()
{
return $this->scopeConfig->isSetFlag(static::XML_PATH_SRS.'logrocket_identify');
}
}
33 changes: 33 additions & 0 deletions Plugin/LogrocketCustomerInfo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace JustBetter\Sentry\Plugin;

use Magento\Customer\CustomerData\Customer;
use Magento\Customer\Helper\Session\CurrentCustomer;
use Magento\Customer\Model\Session;

class LogrocketCustomerInfo
{
protected $currentCustomer;
protected $customerSession;

public function __construct(
CurrentCustomer $currentCustomer,
Session $session
) {
$this->currentCustomer = $currentCustomer;
$this->customerSession = $session;
}

public function afterGetSectionData(Customer $subject, $result)
{
if ($this->customerSession->isLoggedIn()) {
$customer = $this->currentCustomer->getCustomer();

$result['email'] = $customer->getEmail();
$result['fullname'] = $customer->getFirstname().' '.$customer->getLastname();
}

return $result;
}
}
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This module uses the [Magento Deployment Configuration](https://devdocs.magento.
```
'sentry' => [
'dsn' => 'example.com',
'logrocket_key' => 'example/example',
'environment' => null,
'log_level' => \Monolog\Logger::WARNING,
'mage_mode_development' => false,
Expand All @@ -38,10 +39,6 @@ The module is tested on Magento version 2.2.x & 2.3.x with sentry sdk version 2.
## Ideas, bugs or suggestions?
Please create a [issue](https://github.com/justbetter/magento2-sentry/issues) or a [pull request](https://github.com/justbetter/magento2-sentry/pulls).

## Todo
- Integrate custom error pages in composer package - 2020-Q1
- Integrate feedback sentry form in error pages - 2020-Q1

## About us
We’re a innovative development agency from The Netherlands building awesome websites, webshops and web applications with Laravel and Magento. Check out our website [justbetter.nl](https://justbetter.nl) and our [open source projects](https://github.com/justbetter).

Expand Down
20 changes: 18 additions & 2 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,24 @@
<field id="enable_script_tag">1</field>
</depends>
</field>
<field id="sent" translate="label" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<button_label>Send sentry test event</button_label>
<field id="use_logrocket" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Use LogRocket</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="enable_script_tag">1</field>
</depends>
</field>
<field id="logrocket_identify" translate="label" type="select" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<label>LogRocket include user data</label>
<tooltip>Include user ID, name and email to identify logged in users in LogRocket</tooltip>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="enable_script_tag">1</field>
<field id="use_logrocket">1</field>
</depends>
</field>
<field id="sent_sentry" translate="label" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="1">
<button_label>Send Sentry test event</button_label>
<button_url>justbetter_sentry/test/sentry</button_url>
<frontend_model>JustBetter\Sentry\Block\Adminhtml\System\Config\Button</frontend_model>
</field>
Expand Down
17 changes: 12 additions & 5 deletions etc/di.xml
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="JustBetter\Sentry\Model\SentryLog">
<arguments>
<argument name="name" xsi:type="string">SentryLog</argument>
<argument name="handlers" xsi:type="array">
<item name="system" xsi:type="object">Magento\Framework\Logger\Handler\System</item>
</argument>
<argument name="processors" xsi:type="array" />
<argument name="processors" xsi:type="array"/>
<argument name="customerSession" xsi:type="object">Magento\Customer\Model\Session\Proxy</argument>
</arguments>
</type>
Expand All @@ -22,9 +23,15 @@
</arguments>
</type>

<!-- Cannot use plugin https://github.com/magento/magento2/issues/14950 -->
<preference for="Magento\Framework\Logger\Monolog" type="JustBetter\Sentry\Plugin\MonologPlugin" />
<!-- Cannot use plugin https://github.com/magento/magento2/issues/14950 -->
<preference for="Magento\Framework\Logger\Monolog" type="JustBetter\Sentry\Plugin\MonologPlugin"/>
<type name="Magento\Framework\AppInterface">
<plugin disabled="false" name="GlobalExceptionCatcher" type="JustBetter\Sentry\Plugin\GlobalExceptionCatcher" sortOrder="0"/>
<plugin disabled="false" name="GlobalExceptionCatcher" type="JustBetter\Sentry\Plugin\GlobalExceptionCatcher"
sortOrder="0"/>
</type>

<type name="Magento\Customer\CustomerData\Customer">
<plugin name="LogrocketCustomerInfo" type="JustBetter\Sentry\Plugin\LogrocketCustomerInfo"
sortOrder="10" disabled="false"/>
</type>
</config>
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<?= /* @noEscape */ htmlentities("
'sentry' => [
'dsn' => 'example.com',
'logrocket_key' => 'example/example',
'environment' => null,
'log_level' => \Monolog\Logger::WARNING,
'mage_mode_development' => false,
Expand Down
74 changes: 72 additions & 2 deletions view/frontend/templates/script/sentry.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,81 @@
// phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
/** @var \JustBetter\Sentry\Block\SentryScript $block */

if (! $block->canUseScriptTag($block->getNameInLayout())) {
if (!$block->canUseScriptTag($block->getNameInLayout())) {
return;
}
?>

<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise" crossorigin></script>
<script src="https://browser.sentry-cdn.com/4.5.3/bundle.min.js" crossorigin></script>
<script>Sentry.init({ dsn: '<?= $block->escapeUrl(trim($block->getDSN())) ?>' });</script>
<script>Sentry.init({dsn: '<?= $block->escapeUrl(trim($block->getDSN())) ?>'});</script>

<?php if ($block->useLogRocket()) : ?>
<script src="https://cdn.lr-ingest.io/LogRocket.min.js" crossorigin="anonymous"></script>
<script>window.LogRocket && window.LogRocket.init('<?= trim($block->getLogrocketKey()) ?>');</script>
<script>
LogRocket.getSessionURL(sessionURL => {
Sentry.configureScope(scope => {
scope.setExtra("sessionURL", sessionURL);
});
});

<?php if ($block->useLogRocketIdentify()) : ?>

define('customerData',
['jquery', 'Magento_Customer/js/customer-data'],
function ($, customerData) {
'use strict';

var getCustomerInfo = function () {
var customer = customerData.get('customer');

return customer();
};

var isLoggedIn = function (customerInfo) {
return customerInfo && customerInfo.firstname;
};

return function () {
var deferred = $.Deferred();
var customerInfo = getCustomerInfo();

if (customerInfo && customerInfo.data_id) {
deferred.resolve(isLoggedIn(customerInfo), customerInfo);
} else {
customerData.reload(['customer'], false)
.done(function () {
customerInfo = getCustomerInfo()
deferred.resolve(isLoggedIn(customerInfo), customerInfo);
})
.fail(function () {
deferred.reject();
});
}

return deferred;
};

}
);

require(["customerData"], function (customerData) {

customerData().then(function (loggedIn, data) {
if (!loggedIn) {
return;
}

LogRocket.identify(data.websiteId, {
name: data.fullname,
email: data.email
});

});
});


<?php endif; ?>
</script>
<?php endif; ?>

0 comments on commit ee48126

Please sign in to comment.