Skip to content

Instantly share code, notes, and snippets.

@hinnerk-a
Created May 31, 2012 20:31
Show Gist options
  • Save hinnerk-a/2846011 to your computer and use it in GitHub Desktop.
Save hinnerk-a/2846011 to your computer and use it in GitHub Desktop.
WordPress filter hook for logging WP HTTP requests
<?php
function wp_log_http_requests( $response, $args, $url ) {
// set your log file location here
$logfile = plugin_dir_path( __FILE__ ) . '/http_requests.log';
// parse request and response body to a hash for human readable log output
$log_response = $response;
if ( isset( $args['body'] ) ) {
parse_str( $args['body'], $args['body_parsed'] );
}
if ( isset( $log_response['body'] ) ) {
parse_str( $log_response['body'], $log_response['body_parsed'] );
}
// write into logfile
file_put_contents( $logfile, sprintf( "### %s, URL: %s\nREQUEST: %sRESPONSE: %s\n", date( 'c' ), $url, print_r( $args, true ), print_r( $log_response, true ) ), FILE_APPEND );
return $response;
}
// hook into WP_Http::_dispatch_request()
add_filter( 'http_response', 'wp_log_http_requests', 10, 3 );
?>
@mtvbrianking
Copy link

mtvbrianking commented May 4, 2020

Great helper, thanks.

I've modified it a bit to use the default WordPress debug log file.

function fn_log_http_request_response($wp_http_response, $request, $url)
{
    $request = [
        'method' => $request['method'],
        'url' => $url,
        'headers' => $request['headers'],
        'body' => $request['body'],
    ];

    if($wp_http_response instanceof WP_Error) {
        $response = [
            'errors' => $wp_http_response->errors,
            'error_data' => $wp_http_response->error_data,
        ];
    } else {
        $response = [
            'status' => [
                'code' => wp_remote_retrieve_response_code($wp_http_response),
                'message' => wp_remote_retrieve_response_message($wp_http_response),
            ],
            'headers' => wp_remote_retrieve_headers($wp_http_response)->getAll(),
            'body' => wp_remote_retrieve_body($wp_http_response),
        ];
    }

    error_log(print_r([
        'request' => $request,
        'response' => $response,
    ], true));

    return $wp_http_response;
}
add_filter('http_response', 'fn_log_http_request_response', 10, 3);

@hinnerk-a
Copy link
Author

hinnerk-a commented May 5, 2020

Thanks for that great patch!

add_filter('http_response', 'fn_help_log_http_requests', 10, 3 );

You might change the callback function name to 'fn_log_http_request_response'.

@sanishan
Copy link

Is there a way to check which file execute the HTTP request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment