Skip to content

Instantly share code, notes, and snippets.

@hissy
Created March 3, 2018 05:53
Show Gist options
  • Save hissy/52b9596c660c2d7ebdd8395f04c8e60d to your computer and use it in GitHub Desktop.
Save hissy/52b9596c660c2d7ebdd8395f04c8e60d to your computer and use it in GitHub Desktop.
[WordPress Plugin] Logging HTTP API Request Errors
<?php
/*
Plugin Name: HTTP API DEBUG LOG
Version: 0.1
*/
add_action('http_api_debug', function ($response, $context, $class, $r, $url) {
// $response = new WP_Error('http_request_failed', 'debug');
/** @var WP_Error $response */
if (is_wp_error($response)) {
$logfile = WP_CONTENT_DIR . '/http_api_error.log';
$logformat = '[%s] [%s] [%s] [%s] %s';
global $wp_filesystem;
if (!is_object($wp_filesystem)) {
WP_Filesystem();
}
if (!$wp_filesystem->exists($logfile)) {
$wp_filesystem->touch($logfile);
}
$content = $wp_filesystem->get_contents($logfile);
$wp_filesystem->put_contents(
$logfile,
$content = $content . PHP_EOL . sprintf(
$logformat,
(new DateTime())->format('Y-m-d H:i:s'),
$context,
$class,
$url,
$response->get_error_message()
),
FS_CHMOD_FILE
);
}
}, 10, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment