Snippet for WordPress plugin Simple History Log that logs https request made and how long each request took

mgibbs189

{{gist file=”simple-history-log-http-requests-time.php” lang=”php”}}
<?php

/**
* To use this you first need to install the free plugin Simple History
* https://wordpress.org/plugins/simple-history/
*/

// pre_http_request is fired close before the actual request
add_filter( ‘pre_http_request’, function( $retval, $r, $url ) {

$key = md5( $url );

$GLOBALS[“sh_http_log_{$key}”] = microtime(true);

return $retval;

}, 10, 3);

// http_api_debug is fired directly after the request
add_action( ‘http_api_debug’, function( $response, $type, $class, $args, $url ) {

$key = md5( $url );
$globals_key = “sh_http_log_{$key}”;

if ( empty( $GLOBALS[$globals_key] ) ) {
return;
}

$time_taken = microtime(true) – $GLOBALS[$globals_key];

$request_method = isset( $args[“method”] ) ? $args[“method”] : “Unknown”;

$context = [
“url” => $url,
“time_taken” => $time_taken,
“request_method” => $request_method,
“_response” => SimpleHistory::json_encode($response),
“_type” => SimpleHistory::json_encode($type),
“_class” => SimpleHistory::json_encode($type),
“_args” => SimpleHistory::json_encode($args),
“_url” => SimpleHistory::json_encode($url)
];

SimpleLogger()->debug( “http_api_debug: ‘{request_method}’ request to ‘{url}’ took {time_taken} seconds”, $context );

}, 10, 5);

{{/gist}}