Can Google Analytics email me if (crashes and) exceptions occur? - google-analytics

Google Analytics is correctly reporting exceptions thrown by my Android app. And I can use Scheduled Emails to send this report to me. However, receiving a daily email when there isn't anything to report (i.e., the report tells me that zero exceptions occurred) is tedious. Thus, I'd like to receive emails only when there is something to report (i.e., the report tells me that one or more exceptions occurred). It seems that Custom Alerts can be used for this purpose. However, Custom Alerts do not appear to be compatible with Exceptions. This leads me to my question.
Can Custom Alerts be configured to provide email notification on exceptions?
Or, more generally,
Can Google Analytics be configured to provide email notification on exceptions?
Also, does this work for crashes too?
UPDATE (22 Nov 2015, 1 Dec 2015)
(Partial) answer. I provide an answer that enables a server (not Google Analytics) to be configured to provide email notification on exceptions, which is probably a sufficient solution for many.
(Almost an) answer. jakub-kriz has provided a detailed answer, but it does not work as-is. Building upon the answer, I was able to configure Google Analytics to email when no exceptions occur. This is the exact opposite of what is required. Unfortunately, I have been unable to get emails when one or more exceptions occur.
Alternate direction. jakub-kriz has proposed an alternative solution, whereby normal events are used, rather than exception events. I haven't tried this direction.
A complete solution has not yet been proposed.

It is possible, but not in a direct way, you have to hookup you analytics quite dirty.
1) Configuration in Analytics Admin
Create two filters in Admin -> View -> Filters -> Custom -> Advanced
Create filter that listens on hitType exception and set Event Category - Exception
Create filter that replicates Exception description into Event Action
2) Create custom Goal
Create two filters in Admin -> View -> Goals -> Custom -> Event
Event Category equals Exception
3) Create Custom Alert
Custom alert by Goal containg exception
Do not forget your email
Try this and let me know!

To get report on Mail Id there is no way to send directly from google analytics. We can send this error report handling it and send it to programmatically to mail id from our app.

A server (not Google Analytics) can be configured to provide email notification on exceptions, which is probably a sufficient solution for many.
First, you need a service account, which can be created https://console.developers.google.com/project/_/apiui/credential. You'll create a key file (MyAnalytics.p12).
Secondly, we configure our analytics client (MyAnalytics.php):
<?php
//You'll need to install google-api-php-client
//(https://github.com/google/google-api-php-client)
require_once 'Google/autoload.php';
class MyAnalytics
{
//When logged into Google Analytics you'll have a URL that looks
//something like https://www.google.com/analytics/web/?authuser=0#home/a00w11p22/
//Your profile id is everything after the p
const PROFILE_ID = '22';
//This is the service account email that you constructed in step 1
const SERVICE_ACCOUNT_EMAIL = 'blah#developer.gserviceaccount.com';
//This is the file that you constructed in step 1.
const KEY_FILE_LOCATION = 'MyAnalytics.p12';
private $client;
private $analytics;
private $cred;
public function __construct() {
$this->client = new Google_Client();
$this->analytics = new Google_Service_Analytics($this->client);
$key = file_get_contents(self::KEY_FILE_LOCATION);
$this->cred = new Google_Auth_AssertionCredentials(
self::SERVICE_ACCOUNT_EMAIL,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
}
public function getAnalytics() {
$this->client->setAssertionCredentials($this->cred);
if($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($this->cred);
}
return $this->analytics;
}
}
?>
Thirdly, we query and report on exceptions (exceptions.php):
<?php
require_once 'MyAnalytics.php';
$myAnalytics = new MyAnalytics();
$analytics = $myAnalytics->getAnalytics();
$results = $analytics->data_ga->get(
'ga:' . MyAnalytics::PROFILE_ID,
'yesterday',
'today',
'ga:exceptions'
);
$a = $results->getTotalsForAllResults();
$count = $a['ga:exceptions'];
echo $count;
if (is_numeric($count) && $count > 0) {
//handle the exception, e.g., send an email
//(cf. https://stackoverflow.com/a/5335311/3664487)
}
?>
Fourth, configure cron to run exceptions.php (cf. https://stackoverflow.com/a/22358929/3664487).

Related

User-Id for Push-Notification on Actions for Google

I try to make a push notification for my google assistant app.
I used the sendNotification Code form the google developer site: https://developers.google.com/actions/assistant/updates/notifications
I am coding Java.
Everything is working, expect getting the correct user id.
When I hardcode my user it works, but how do I get the user id in the code?
I tried following code:
Argument arg_userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
String userId = request.getUser().getUserId();
--> I get "java.lang.reflect.InvocationTargetException"
String userId = arg_userId.getRawText();
--> same Exception
There are two problems with the approach you're taking to get the notification ID:
The ID attached to the user object is deprecated and probably unavailable.
This wasn't the ID you wanted anyway.
In the response where the user finalizes the notification, that response includes an ID which you should get and store. Since you're using Java, the code might look something like this:
ResponseBuilder responseBuilder = getResponseBuilder(request);
Argument permission = request.getArgument(ConstantsKt.ARG_PERMISSION);
if (permission != null) {
Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
// code to save intent and userID in your db
responseBuilder.add("Ok, I'll start alerting you.").endConversation();
} else {
responseBuilder.add("Ok, I won't alert you.");
}
return responseBuilder.build();

I am noticing double entry (cpc and organic) for the same user ? little confused

I'm noticing double entry in google analytics. I have multiple ocurrences where it looks like the user came from the CPC campaign (which always has a 0s session duration) but that very same user also has an entry for "organic" and all the activities are logged under that.
My site is not ranked organically for those keywords. Unless a so many users come to my site, leave, and google for my "brand name" on google and revisits, this doesn't make sense.
I'm a little confused. Here's the report:
preview from google analytics dashboard
Based on the additional information in your comment, that the sites is a Single Page Application (SPA), you are most likely facing the problem of 'Rogue Referral'.
If this is the case, what happens, is that you overwrite the location field in the Analytics hit, losing the original UTM parameters, whereas referral is still sent with the hit, so Analytics recognizes the second hit as a new traffic source. One of the solutions is to store the original page URL and send it as the location, while sending the actual visited URL in the page field.
A very good article on this topic with further tips, by Simo Ahava, is available for your help.
Also please note, that as you have mentioned, that the first hit shows 0 second time on page, you might need to check, whether the first visited page is sent twice. E.g. sending a hit on the traditional page load event, and sending a hit for the same page as a virtual page view.
I have come up with a solution to this problem in a Gatsby website (a SPA), by writing the main logic in the gatsby-browser.js file, inside the onRouteUpdate function.
You can use this solution in other contexts, but please note that the code needs to run at the first load of the page and at every route change.
If you want the solution to work in browsers that do not support URLSearchParams I think you can easily find a polyfill.
Function to retrieve the parameters
// return the whole parameters only if at least one of the desired parameters exists
const retrieveParams = () => {
let storedParams;
if ('URLSearchParams' in window) {
// Browser supports URLSearchParams
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
const requestedParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'gclid'];
const hasRequestedParams = requestedParams.some((param) => {
// true if it exists
return !!params.get(param);
});
if (hasRequestedParams) {
storedParams = params;
}
}
return storedParams;
}
Create the full URL
// look at existing parameters (from previous page navigations) or retrieve new ones
const storedParams = window.storedParams || retrieveParams();
let storedParamsUrl;
if (storedParams) {
// update window value
window.storedParams = storedParams;
// create the url
const urlWithoutParams = document.location.protocol + '//' + document.location.hostname + document.location.pathname;
storedParamsUrl = `${urlWithoutParams}?${storedParams}`;
}
Send the value to analytics (using gtag)
// gtag
gtag('config', 'YOUR_GA_ID', {
// ... other parameters
page_location: storedParamsUrl ?? window.location.href
});
or
gtag('event', 'page_view', {
// ... other parameters
page_location: storedParamsUrl ?? window.location.href,
send_to: 'YOUR_GA_ID'
})

How can I catch a WooCommerce webhook delivery and get the response?

I'm attempting to write some functionality to more intelligently control the way WooCommerce handles failed webhooks. Currently, it just disables the webhook after 5 failed tries. I'm trying to make it so that it makes attempts in progressively larger time intervals until it either succeeds, or finally fails after the time interval reaches one day (86400).
The problem is, I can't find a way to catch a failed webhook. I'm trying to grab the response code and webhook ID from the woocommerce_webhook_delivery hook as defined in WC_Webhook::deliver() in the WC source. The problem is... even though my test WC webhooks are firing and being delivered fine, I can't ever detect that this method is running, even though all of the methods responsible for delivering webhooks refer back to it. I tried XDebug, sticking error_logs in there in the event that they were running in the background. Still no dice. Therefore, my idea of catching the woocommerce_webhook_delivery isn't working, and I don't really know of another, easier way.
Here's what little code I have so far on this, if I can detect the response code I can handle the rest....
WC_WebhookBackoff {
protected $webhook;
protected $webhook_id;
public function __construct() {
add_action('woocommerce_webhook_delivery', [$this, 'catch_webhook_failure'], 1, 5);
}
public function hooks() {
}
public function catch_webhook_failure($http_args, $response, $duration, $arg, $id) {
$failed_hooks = get_option( '_failed_wc_webhooks', true ) ? json_decode(get_option( '_wds_failed_wc_webhooks', true ) ) : [];
error_log("This should be called.");
if ( 200 !== $response ) {
$failed_hooks = [];
$this->update_failed_hooks();
}
}
[...snip...]
And yeah, this is definitely being instantiated and the hook is definitely being registered.
For reference, here's the hook I'm looking at:
do_action( 'woocommerce_webhook_delivery', $http_args, $response, $duration, $arg, $this->get_id() );
Any help is greatly appreciated.
I wanted to do the same thing essentially (capturing information about the response to my webhooks). Here's how I did it.
add_action('woocommerce_webhook_delivery', function($http_args, $response, $duration, $arg, $webhook_id) {
// do whatever you want to here
..
}, 1, 5);
Please note that I've set priority to 1 instead of the default 10, because with 10 it didn't work (I don't have a complete understanding of WordPress hook priorities yet). 5 at the end means the hook receives 5 parameters. This way my callback gets invoked.
I had a hook setup to fire when I update products. I updated my products description and my callback function was invoked. Please note, that updating the webhook (changing the endpoint or whatever) didn't invoke the callback function (not sure why, because it sends a ping to delivery address).
For testing, I also used this filter.
apply_filters('woocommerce_webhook_deliver_async', function() {
return false;
});
This essentially bypasses WooCommerce's action scheduler, the webhook's payload will be delivered immediately instead of sitting in a queue until it gets dispatched.

Google Analytics API Multiple Queries - Second Function?

This is a rather newbie question, please bear with me...
I have successfully authorised my Google Analytics API account and am making the following call, which successfully prints the bounce rate.
I want to add more queries on for things such as pageviews and sessions, how do i do this?
It's the functions which are confusing me, do i need to create a new function for each query?
Thanks In Advance!
Tom
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'today',
'today',
'ga:bouncerate');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
The following part of your code is what actually makes the API request:
$analytics->data_ga->get(
'ga:' . $profileId,
'today',
'today',
'ga:bouncerate');
If you want to make additional queries, you'll have to call the $analytics->data_ga->get() method again. You don't need to write a new function for each query (if you don't want to), but you will need to invoke $analytics->data_ga->get() each time. How you choose to reuse that bit is up to you.

Create chat group in SignalR

How can I create a chat group in SignalR? I tried to find some examples and they weren't helpful. Any help would be appreciated. Here is what I've come up with so far:
public void CreateGroup(string currentUserId, string toConnectTo)
{
string strGroupName = GetUniqueGroupName(currentUserId, toConnectTo);
string connectionId_To = OnlineUser.userObj.Where(item => item.userId == toConnectTo).Select(item => item.connectionId).SingleOrDefault();
if (!string.IsNullOrEmpty(connectionId_To))
{
Groups.Add(Context.ConnectionId, strGroupName);
Groups.Add(connectionId_To, strGroupName);
Clients.Caller.setChatWindow(strGroupName, toConnectTo);
}
}
It's not such easy to create a user friendly chat group that I'm currently working on.
I use sql database, user can register, login, logout, close browser or phone app without logout.
user can create own group, add members to group, delete member from group.
when user send message, call signalr Server method and store message in sql, then Server send message to all users in the same group. if some users are offline, they read message from sql when online again.
the input for the message can be a 'contenteditable div' so that user can add images and formatted text to the message.
something like that!

Resources