How should I store a log for my plugin

I have a plugin that sends data to a server as part of a transition_post_status action. The server sends a response each time. I want to keep a log of these responses (permanently) that I can display in a table to the user somewhere, like so:

Date | Response
------------------
1/1  | OK
1/2  | Status code 2

What’s the best way to do this? Should I create a new database table, or is there a more convenient way?

Read More

Some background: I’ve tried using the WP_Logging() class, but it doesn’t seem to work correctly when called through an action.

Related posts

Leave a Reply

2 comments

  1. It is not clear exactly what you are doing. For example, I am not sure what the data is that you are saving or where/when it needs to be displayed, but it sounds like you need:

    1. The Transients API
    2. Or the Options API

    However, if your data is very complicated you might want a dedicated table. Without more information, that is the best I’ve got.

  2. How I’ve done it in the end is as follows:

    Because it’s triggered on post_status_transition, each log can be effectively linked to a particular post. Therefore, I can use add/update_post_meta to store the response and timestamp as meta fields for that post.

    To retrieve all logs, I can simply do:

    $logs = array();
            $query_args = array(
                'meta_key' => 'myresponsetimestamp',
                'meta_compare' => 'EXISTS',
                'order' => 'DESC',
                'orderby' => 'meta_value_num'
            );
            $query = new WP_Query($query_args);
            if ( $query->have_posts() ) {
                while ( $query->have_posts() ) {
                    $query->the_post();
                    $post_id = get_the_ID();
                    $logs[] = array(
                        'postid' =>$post_id,
                        'time' => get_post_meta( $post_id, 'myresponsetimestamp', true ),
                        'response' =>get_post_meta( $post_id, 'myresponse', true )
                    );
                }
            }
            wp_reset_postdata();