Monitoring Google Analytics with NetCrunch

We will show you a small example which monitors the page views of your webpage. For more information about what is possible to monitor with Google Analytics please visit the Google Analytics webpage.

For monitoring information from Google Analytics with NetCrunch you can use different approaches.

We will show you a small example which monitors the page views of your webpage. For more information about what is possible to monitor with Google Analytics please visit the Google Analytics webpage.

Setting up Google Analytics

If you have Google Analytics already running you can skip to section Setting up the API.

  1. Sign up for Analytics with your Google Account. SignUp Analytics

  2. Create a new account as shown in the screenshot. New Account

  3. Agree to the terms.

  4. The following page will show you Tracking ID which you need to setup analytics on your webpage. Copy the JavaScript code and include it in the header of your page. e.g.:

     <!DOCTYPE html>
         <html>
         <head>
               <!--your header information -->
               <!-- Google Analytics -->
         <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new          Date();a=s.createElement(o),  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
           ga('create', 'UA-XXXX-Y', 'auto');
           ga('send', 'pageview');
           <!-- End Google Analytics -->
         </script>
     </head>
      <body>
          <h1>Testpage</h1>
           <p>Stuff....</p>
      </body>
    </html>
    

UA-XXXX-Y needs to be your Tracking ID. More details about analytics.js can be find here.

Setting up the API

  1. Now create a new project in the Google Developers Console. Create Project
  2. After creating the project click on APIs & auth -> Credentials and Add credentials -> Service account to get the API key. Add Credentials
  3. Choose key type P12 and download the key. Key 4 Copy the email address (XXXXXXXXX@developer.gserviceaccount.com) from the following view. Acount Email 5.Enable the Analytics API by switching to APIs & auth -> APIs and search for analytics. Activate API Activate API
  4. Switch to the Analytics Account and add a new user in the Admin panel. More details about adding and modifying users can be found here. Add User
  5. Go to the View Settings and copy the View ID for later. Analytics Prefferences View ID

  6. Convert the p12 file with OpenSSL to a pem file. The password should be notasecret (see step 3 of this section). OpenSSL for windows can be found here.

      openssl pkcs12 -in XXXXX.p12 -nocerts -nodes -out testProject.pem
    

Note: After setting up Analytics and the Developer Console it can take some time until page visits are shown in Google Analytics. You can check that by visiting you page and checking it in the Dashboard of Analytics.

Using Node.js to transfer the data to NetCrunch

  1. This script requires googleapi and http. You can install these packages with npm.

    npm install googleapis http
    
  2. Create a new JavaScript file "googleanalytics.js" and copy the *.pem file into the same folder as the script. You need to modify the following variables: SERVICE_ACCOUNT_EMAIL (Service Account Email Address, see step 4 of this section) SERVICE_ACCOUNT_KEY_FILE (The path to the *.pem file, if you stored it in the same directory as the googleanalytics.js you don’t need to modify the path just the name of the file) ID (View ID, see step 7) NCAPIKEY (The API key set in NetCrunch) NCSERVER (Address of you NetCrunch server)

    var    http = require('http'),     googleapis = require('googleapis'),    JWT = googleapis.auth.JWT,
             analytics = googleapis.analytics('v3'),
    
    //   add here the service account email address
         SERVICE_ACCOUNT_EMAIL = "XXXXXXXXXX@developer.gserviceaccount.com",
    
    //   the key created in the google developer console
         SERVICE_ACCOUNT_KEY_FILE = __dirname + '/testProject.pem',
    
    //   View ID
        ID = '107091566',
    
    //   Your NetCrunch API key
         NCAPIKEY = "MTQ1Q0Y0M0M=xxxx",
    
    //   Address of the NetCrunch server
         NCSERVER = '192.168.2.4',
    
    authClient = new JWT(SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_KEY_FILE, null,
        ['https://www.googleapis.com/auth/analytics.readonly']
    );
    
    authClient.authorize(function (err, tokens) {
    'use strict';
    
    if (err) {
        console.log(err);
        return;
    }
    
    //  request to google analytics, show the pageviews from today
    analytics.data.ga.get({
        auth: authClient,
        'ids': 'ga:' + ID,
        'start-date': 'today',
        'end-date': 'today',
        'metrics': 'ga:pageviews'
    }, function (err, result) {
        console.log(err);
        console.log(result);
        var pageviews = result.totalResults;
    
        //creating json data which will be send to NetCrunch
        var jsonData = JSON.stringify({
            retain: 6,//time to keep the information alive if no new data is arriving
            apikey: NCAPIKEY,
            counters: {
                "Homepage/Views": pageviews
            }
        });
    
        //sending data to NetCrunch
        var options = {
            hostname: NCSERVER,
            port: '80',
            path: '/ncintf/rest/1/openmon/update',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        };
        var req = http.request(options, function (res) {
            console.log('STATUS: ' + res.statusCode);
            console.log('HEADERS: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                console.log('Response: ' + chunk);
            });
        });
    
        req.write(jsonData);
        req.end();
        console.log(JSON.parse(jsonData));
      });
    });
    

Now you just need to configure the Open Monitor to display the data.

To get more information about functionalities of Analytics read about Analytics Reporting.

NetCrunch. Answers not just pictures

Maps → Alerts → Automation → Intelligence