Search code examples
google-analytics

Can't log events in Google Analytics / GA4


I can't log custom events in GA4. I add it to my site with tag manager like this:

  <script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  </script>
  <!-- Google Tag Manager -->
  <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','GTM-XXXX1234');</script>
  <!-- End Google Tag Manager -->

The first four lines are what others seem to suggest is required to allow the following to fire my custom event in GA4:

gtag('event', 'my_event', {
    'event_date': document.getElementById('date').value,
    'param1': 'false',
    'param2': 3,
    'param3': thing.is_done? 'correct' : 'incorrect'
}); 

The gtag call is within a function, the rest of which executes without error (and the gtag call doesn't seem to cause any issues). But in my browser's debugger I don't see any requests to Google (should I?) and in the 'Real Time' report in GA4 I don't seem my event (I'm assuming I should?). Otherwise GA4 seems to be working, I get page_view events, session_start etc.

Anyone know how I can debug this?


Solution

  • Either do tracking via GTM (the best practice) OR do it via gtag (an odd practice). But don't attempt to do both. While it can work, it will lead to confusion and mistakes.

    Good thinking on not seeing any requests to google in the network tab. Yes, if the tracking works, you should be able to see the requests to the collect? endpoint in the network tab. And yes, you should see your hits in the real time report. As well as the debug view in GA4. But really, the most useful thing is the network tab or Adswerve's dataLayer Explorer extension that just displays all analytics network hits in the console in a very neat way.

    Your problem is likely in the absence of the gtag library, so after you push stuff in the DL through your gtag() function, there's no one to pick it up and send it to where it should go.

    The events you seem to be getting are likely coming from the GTM set up. You should stop doing what you're doing and keep using GTM.

    You don't need this piece:

      function gtag(){dataLayer.push(arguments);}
    

    Just define the dataLayer object as you do and .push() your stuff into it. Then in GTM, make triggers, variables and tags to pick that info and send it to GA. This makes all your tracking a lot easier to manage.

    Google has a good tutorial on it here.