• Resolved bsmolyanov

    (@bsmolyanov)


    I tried to come up with code for a Custom Logger for logged-in users page visits tracking, based on the example in the documentation.

    Any suggestions are welcome. Below is my code:

    if (!class_exists('\Simple_History\Loggers\Logger')) {
        return;
    }
    
    add_action(
        'simple_history/add_custom_logger',
        function ($simple_history) {
            $simple_history->register_logger('User_Page_Visit_Logger');
        }
    );
    
    class User_Page_Visit_Logger extends \Simple_History\Loggers\Logger
    {
        public $slug = 'User_Page_Visit_Logger';
    
        public function getInfo()
        {
            return array(
                'name' => __('User Page Visit Logger', 'simple-history'),
                'description' => __('Logs page visits by logged-in users', 'simple-history'),
                'capability' => 'read',
                'messages' => array(
                    'page_visit' => __('User {user_id} ({user_name}, {user_email}) visited "{post_title}" ({post_permalink})', 'simple-history'),
                ),
                'labels' => array(
                    'search' => array(
                        'label' => __('User Page Visits', 'simple-history'),
                        'options' => array(
                            __('Page Visits', 'simple-history') => array(
                                'page_visit',
                            ),
                        ),
                    ),
                ),
            );
        }
    
        public function loaded()
        {
            if (is_user_logged_in()) {
                add_action('wp', array($this, 'log_page_visit'));
            }
        }
    
        public function log_page_visit()
        {
            $current_user = wp_get_current_user();
            $post = get_queried_object();
    
            if ($current_user && $post) {
                $context = array(
                    '_initiator' => LogInitiators::WEB_USER,
                    'user_id' => $current_user->ID,
                    'user_name' => $current_user->display_name,
                    'user_email' => $current_user->user_email,
                    'post_title' => get_the_title($post),
                    'post_permalink' => get_permalink($post),
                );
    
                $this->infoMessage('page_visit', $context);
            }
        }
    }
    
Viewing 8 replies - 1 through 8 (of 8 total)
  • Plugin Author eskapism

    (@eskapism)

    Nice! I haven’t tested it but it seems like it works, right?

    One small thing I noticed was that you call the function getInfo(). I have updated the code to use WordPress PHP Coding Standards so the function should be called get_info(). Probably that’s my fault and the documentation is out of date somewhere…

    Thread Starter bsmolyanov

    (@bsmolyanov)

    Thanks a lot, @eskapism !

    Unfortunately, something seems to be wrong. I place the code in functions.php and then I get the following PHP errors. Also it prevents the other loggers from displaying their messages as well.

    There are the errors I am getting:

    Got error 'PHP message: PHP Fatal error:  Allowed memory size of 2147483648 bytes exhausted (tried to allocate 557056 bytes) in /home/....../wp-includes/class-wpdb.php on line 2459'

    and

    Got error 'PHP message: WordPress database error Commands out of sync; you can't run this command now for query UPDATE wp_options SET option_value = '1695284706' WHERE option_name = 'action_scheduler_lock_async-request-runner' made by shutdown_action_hook, do_action('shutdown'), WP_Hook->do_action, WP_Hook->apply_filters, ActionScheduler_QueueRunner->maybe_dispatch_async_request, ActionScheduler_OptionLock->set, update_option, QM_DB->queryPHP message: WordPress database error Commands out of sync; you can't run this command now for query SELECT COUNT(DISTINCT claim_id) FROM wp_actionscheduler_actions WHERE claim_id != 0 AND status IN ( 'pending', 'in-progress') made by shutdown_action_hook, do_action('shutdown'), WP_Hook->do_action, WP_Hook->apply_filters, ActionScheduler_QueueRunner->maybe_dispatch_async_request, ActionScheduler_AsyncRequest_QueueRunner->maybe_dispatch, ActionScheduler_AsyncRequest_QueueRunner->allow, ActionScheduler_Abstract_QueueRunner->has_maximum_concurrent_batches, ActionScheduler_DBStore->get_claim_count, QM_DB->queryPHP message: WordPress database error Commands out of sync; you can't run this command now for query SELECT a.action_id FROM wp_actionscheduler_actions a WHERE 1=1 AND a.status IN ('pending') AND a.scheduled_date_gmt <= '2023-09-21 08:24:06' LIMIT 0, 5 made by shutdown_action_hook, do_action('shutdown'), WP_Hook->do_action, WP_Hook->apply_filters, ActionScheduler_QueueRunner->maybe_dispatch_async_request, ActionScheduler_AsyncRequest_QueueRunner->maybe_dispatch, ActionScheduler_AsyncRequest_QueueRunner->allow, ActionScheduler_Store->has_pending_actions_due, ActionScheduler_DBStore->query_actions, QM_DB->query'

    I would really appreciate your input to make this custom logger work.

    Thanks!

    • This reply was modified 1 year, 2 months ago by bsmolyanov.
    Plugin Author eskapism

    (@eskapism)

    There was some errors in my example code. I have now fixed my code + your code and this is the result that is tested to work:

    First put this code in your functions.php file (or in your plugin, or where you usually put your custom code):

    <?php
    
    // Load and register custom logger.
    add_action(
        'simple_history/add_custom_logger',
        function ($simple_history) {
            require_once __DIR__ . '/class-user-page-visit-logger.php';
            $simple_history->register_logger(User_Page_Visit_Logger::class);
        }
    );

    The create the file class-user-page-visit-logger.php in the same dir and add the actual logger code there:

    <?php
    
    class User_Page_Visit_Logger extends \Simple_History\Loggers\Logger
    {
        public $slug = 'User_Page_Visit_Logger';
    
        public function get_info()
        {
            return array(
                'name' => __('User Page Visit Logger', 'simple-history'),
                'description' => __('Logs page visits by logged-in users', 'simple-history'),
                'capability' => 'read',
                'messages' => array(
                    'page_visit' => __('User {user_id} ({user_name}, {user_email}) visited "{post_title}" ({post_permalink})', 'simple-history'),
                ),
                'labels' => array(
                    'search' => array(
                        'label' => __('User Page Visits', 'simple-history'),
                        'options' => array(
                            __('Page Visits', 'simple-history') => array(
                                'page_visit',
                            ),
                        ),
                    ),
                ),
            );
        }
    
        public function loaded()
        {
            if (is_user_logged_in()) {
                add_action('wp', array($this, 'log_page_visit'));
            }
        }
    
        public function log_page_visit()
        {
            $current_user = wp_get_current_user();
            $post = get_queried_object();
    
            if ($current_user && $post) {
                $context = array(
                    '_initiator' => \Simple_History\Log_Initiators::WEB_USER,
                    'user_id' => $current_user->ID,
                    'user_name' => $current_user->display_name,
                    'user_email' => $current_user->user_email,
                    'post_title' => get_the_title($post),
                    'post_permalink' => get_permalink($post),
                );
    
                $this->info_message('page_visit', $context);
            }
        }
    }
    
    Thread Starter bsmolyanov

    (@bsmolyanov)

    Thank you very much for your time and effort, @eskapism !

    I implemented the code and visits are recorded as expected!

    Thread Starter bsmolyanov

    (@bsmolyanov)

    Hi?@eskapism! The custom logger code you provided is working almost perfectly!

    I recently noticed that each history entry starts initiated by it starts with a gray avatar logo followed by ‘Anonymous web user‘. Then, in the message itself it specifies, as expected, all the user/visited page details.

    All the other log entries start with the user’s display name (as a link to the user profile) and the user’s email address, which is the expected behavior.

    Is there a way to correct this and make the custom logger entries feel ‘native’ in the log?

    Thank you very much!

    Thread Starter bsmolyanov

    (@bsmolyanov)

    Managed to solve this by replacing LogInitiators::WEB_USER with LogInitiators::WP_USER.

    Thread Starter bsmolyanov

    (@bsmolyanov)

    Something else came to my mind ??

    Is there a way to print the visited page/post title as a link?

    Currently, the title and the link are in plain text like this:

    visited “{post_title}” ({post_permalink})

    Thank you!

    Thread Starter bsmolyanov

    (@bsmolyanov)

    I will start a new thread based on the new topic.

    Thank you!

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Custom Logger Code’ is closed to new replies.