How to use a terminate kernel event to log page access statistics?
The comments you got are golden, my answer is along the lines of what @IvanJaros suggested, but follows a simpler approach. And take care to check the case of external caching (if any is in play).

The following should make your current approach work.

public function logAccess(PostResponseEvent $event) {

  $request_format = $event-&gt;getRequest()-&gt;getRequestFormat();

  if ($request_format === 'html') {
    // \Drupal::database()-&gt;
  }
  else {
    // Do other stuff.
  }
  ...


This snippet tries to detect requests with the html format (i.e. page requests) and will ignore other ones, like e.g. application/json.

Good luck!