Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Created October 22, 2019 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpmudev-sls/6a42451dad898f748339d065b3624b9f to your computer and use it in GitHub Desktop.
Save wpmudev-sls/6a42451dad898f748339d065b3624b9f to your computer and use it in GitHub Desktop.
[General] - Log all Cron Runs. Creates log files including all cron actions when triggered
<?php
/**
* Plugin Name: [General] - Log all Cron Runs
* Plugin URI: https://premium.wpmudev.org/
* Description: Creates log files including all cron actions when triggered
* Author: Panos Lyrakis @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WPMUDEV_Log_Cron_Runs' ) ) {
class WPMUDEV_Log_Cron_Runs {
private static $_instance = null;
private static $cron_actions = array();
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Log_Cron_Runs();
}
return self::$_instance;
}
private function __construct() {
if ( empty( self::$cron_actions ) ) {
$this->list_cron_actions();
$this->hook_cron_actions();
}
}
private function list_cron_actions() {
$cron_jobs = get_option( 'cron' );
foreach ( $cron_jobs as $key => $cron_job ) {
if ( ! is_array( $cron_job ) || empty( $cron_job ) ) {
continue;
}
self::$cron_actions[] = array_keys( $cron_job )[0];
}
}
private function hook_cron_actions() {
foreach ( self::$cron_actions as $hook ) {
add_action( $hook, [ $this, 'log_action_triggered' ] );
}
}
public function log_action_triggered() {
$hook_name = current_filter();
if ( ! empty( $hook_name ) ) {
$this->log( $hook_name );
}
}
private function log( $message ) {
if ( ! defined( "WP_DEBUG_LOG" ) || ! WP_DEBUG_LOG ) {
return;
}
$time = date( 'd-M-Y H:i:s' );
error_log(
"[ {$time} ] => {$message}\n\n",
3,
WP_CONTENT_DIR . "/wp-cronruns-" . date( 'd-m-Y' ) . ".log"
);
}
}
if ( ! function_exists( 'wpmudev_log_cron_runs' ) ) {
function wpmudev_log_cron_runs() {
return WPMUDEV_Log_Cron_Runs::get_instance();
};
add_action( 'plugins_loaded', 'wpmudev_log_cron_runs', 10 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment