I would look into how other Analytics plugins work. For example this Analytics plugin: https://moodle.org/plugins/local_analytics
They are using these Moodle callbacks to inject their logic on every page: https://github.com/bmbrands/moodle-local_analytics/blob/master/lib.php
They are using these Moodle callbacks to inject their logic on every page: https://github.com/bmbrands/moodle-local_analytics/blob/master/lib.php