You are here

class UltimateCronDatabaseLogger in Ultimate Cron 7.2

Class for using database as log storage.

Hierarchy

Expanded class hierarchy of UltimateCronDatabaseLogger

1 string reference to 'UltimateCronDatabaseLogger'
database.inc in plugins/ultimate_cron/logger/database.inc

File

plugins/ultimate_cron/logger/database.class.php, line 14
Database logger for Ultimate Cron.

View source
class UltimateCronDatabaseLogger extends UltimateCronLogger {
  public $options = array();
  public $log_entry_class = '\\UltimateCronDatabaseLogEntry';

  /**
   * Constructor.
   */
  public function __construct($name, $plugin, $log_type = ULTIMATE_CRON_LOG_TYPE_NORMAL) {
    parent::__construct($name, $plugin, $log_type);
    $this->options['method'] = array(
      ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED => t('Disabled'),
      ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE => t('Remove logs older than a specified age'),
      ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN => t('Retain only a specific amount of log entries'),
    );
  }

  /**
   * Default settings.
   */
  public function defaultSettings() {
    return array(
      'method' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN,
      'expire' => 86400 * 14,
      'retain' => 1000,
    );
  }

  /**
   * Cleanup logs.
   */
  public function cleanup() {
    $jobs = _ultimate_cron_job_load_all();
    $current = 1;
    $max = 0;
    $count_deleted = array();
    foreach ($jobs as $job) {
      if ($job
        ->getPlugin($this->type)->name === $this->name) {
        $max++;
      }
    }
    foreach ($jobs as $job) {
      if ($job
        ->getPlugin($this->type)->name === $this->name) {
        $deleted_logs = $this
          ->cleanupJob($job);
        $class = _ultimate_cron_get_class('job');
        if ($class::$currentJob) {
          $class::$currentJob
            ->setProgress($current / $max);
          $current++;
        }
        if ($deleted_logs > 0) {

          // Store number of deleted messages for each job.
          $count_deleted[$job->name] = $deleted_logs;
        }
      }
    }
    if (!empty($count_deleted)) {
      watchdog('database_logger', '@count_entries log entries removed for @jobs_count jobs', array(
        '@count_entries' => array_sum($count_deleted),
        '@jobs_count' => count($count_deleted),
      ), WATCHDOG_INFO);
    }
  }

  /**
   * Cleanup logs for a single job.
   */
  public function cleanupJob($job) {
    $settings = $job
      ->getSettings('logger');
    switch ($settings['method']) {
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED:
        return 0;
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE:
        $expire = $settings['expire'];

        // Let's not delete more than ONE BILLION log entries :-o.
        $max = 10000000000;
        $chunk = 100;
        break;
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN:
        $expire = 0;
        $max = db_query("SELECT COUNT(lid) FROM {ultimate_cron_log} WHERE name = :name", array(
          ':name' => $job->name,
        ))
          ->fetchField();
        $max -= $settings['retain'];
        if ($max <= 0) {
          return 0;
        }
        $chunk = min($max, 100);
        break;
      default:
        watchdog('ultimate_cron', 'Invalid cleanup method: @method', array(
          '@method' => $settings['method'],
        ));
        return 0;
    }

    // Chunked delete.
    $count = 0;
    do {
      $lids = db_select('ultimate_cron_log', 'l')
        ->fields('l', array(
        'lid',
      ))
        ->condition('l.name', $job->name)
        ->condition('l.start_time', microtime(TRUE) - $expire, '<')
        ->range(0, $chunk)
        ->orderBy('l.start_time', 'ASC')
        ->orderBy('l.end_time', 'ASC')
        ->execute()
        ->fetchAll(PDO::FETCH_COLUMN);
      if ($lids) {
        $count += count($lids);
        $max -= count($lids);
        $chunk = min($max, 100);
        db_delete('ultimate_cron_log')
          ->condition('lid', $lids, 'IN')
          ->execute();
      }
    } while ($lids && $max > 0);
    return $count;
  }

  /**
   * Label for setting.
   */
  public function settingsLabel($name, $value) {
    switch ($name) {
      case 'method':
        return $this->options[$name][$value];
    }
    return parent::settingsLabel($name, $value);
  }

  /**
   * Settings form.
   */
  public function settingsForm(&$form, &$form_state, $job = NULL) {
    $elements =& $form['settings'][$this->type][$this->name];
    $defaults =& $form_state['default_values']['settings'][$this->type][$this->name];
    $values =& $form_state['values']['settings'][$this->type][$this->name];
    $elements['method'] = array(
      '#type' => 'select',
      '#title' => t('Log entry cleanup method'),
      '#description' => t('Select which method to use for cleaning up logs.'),
      '#options' => $this->options['method'],
      '#default_value' => $values['method'],
      '#fallback' => TRUE,
      '#required' => TRUE,
    );
    $states = array(
      'expire' => array(),
      'retain' => array(),
    );
    if ($job) {
      $states['expire'] = array(
        '#states' => array(
          'visible' => array(
            ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array(
              'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE,
            ),
          ),
          'enabled' => array(
            ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array(
              'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE,
            ),
          ),
        ),
      );
      $states['retain'] = array(
        '#states' => array(
          'visible' => array(
            ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array(
              'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN,
            ),
          ),
          'enabled' => array(
            ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array(
              'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN,
            ),
          ),
        ),
      );
    }
    $elements['method_expire'] = array(
      '#type' => 'fieldset',
      '#title' => t('Remove logs older than a specified age'),
    ) + $states['expire'];
    $elements['method_expire']['expire'] = array(
      '#parents' => array(
        'settings',
        $this->type,
        $this->name,
        'expire',
      ),
      '#type' => 'textfield',
      '#title' => t('Log entry expiration'),
      '#description' => t('Remove log entries older than X seconds.'),
      '#default_value' => $values['expire'],
      '#fallback' => TRUE,
      '#required' => TRUE,
    ) + $states['expire'];
    $elements['method_retain'] = array(
      '#type' => 'fieldset',
      '#title' => t('Retain only a specific amount of log entries'),
    ) + $states['retain'];
    $elements['method_retain']['retain'] = array(
      '#parents' => array(
        'settings',
        $this->type,
        $this->name,
        'retain',
      ),
      '#type' => 'textfield',
      '#title' => t('Retain logs'),
      '#description' => t('Retain X amount of log entries; this value is per cron job. Setting this to 1000 on sites with 15 cron jobs will store a total of 15000 entries. High values can result in slower log performance.'),
      '#default_value' => $values['retain'],
      '#fallback' => TRUE,
      '#required' => TRUE,
    ) + $states['retain'];
    if ($job) {
      if ($defaults['method'] == ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE) {
        $elements['method_default'] = $elements['method_expire'];
        $elements['method_default']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['expire']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['expire']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
      }
      if ($defaults['method'] == ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN) {
        $elements['method_default'] = $elements['method_retain'];
        $elements['method_default']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['retain']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
        $elements['method_default']['retain']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = '';
      }
    }
  }

  /**
   * Submit handler.
   */
  public function settingsFormSubmit(&$form, &$form_state, $job = NULL) {
    $values =& $form_state['values']['settings'][$this->type][$this->name];
    $defaults =& $form_state['default_values']['settings'][$this->type][$this->name];
    if (!$job) {
      return;
    }
    $method = $values['method'] ? $values['method'] : $defaults['method'];

    // Cleanup form (can this be done elsewhere?)
    switch ($method) {
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED:
        unset($values['expire']);
        unset($values['retain']);
        break;
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE:
        unset($values['retain']);
        break;
      case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN:
        unset($values['expire']);
        break;
    }
  }

  /**
   * Load log entry.
   */
  public function load($name, $lock_id = NULL, $log_types = array(
    ULTIMATE_CRON_LOG_TYPE_NORMAL,
  )) {
    if ($lock_id) {
      $log_entry = db_select('ultimate_cron_log', 'l')
        ->fields('l')
        ->condition('l.lid', $lock_id)
        ->execute()
        ->fetchObject($this->log_entry_class, array(
        $name,
        $this,
      ));
    }
    else {
      $subquery = db_select('ultimate_cron_log', 'l3')
        ->fields('l3', array(
        'name',
        'log_type',
      ))
        ->groupBy('name')
        ->groupBy('log_type');
      $subquery
        ->addExpression('MAX(l3.start_time)', 'start_time');
      $query = db_select('ultimate_cron_log', 'l1')
        ->fields('l1');
      $query
        ->join($subquery, 'l2', 'l1.name = l2.name AND l1.start_time = l2.start_time AND l1.log_type = l2.log_type');
      $query
        ->condition('l2.name', $name);
      $query
        ->condition('l2.log_type', $log_types, 'IN');
      $log_entry = $query
        ->execute()
        ->fetchObject($this->log_entry_class, array(
        $name,
        $this,
      ));
    }
    if ($log_entry) {
      $log_entry->finished = TRUE;
    }
    else {
      $log_entry = new $this->log_entry_class($name, $this);
    }
    return $log_entry;
  }

  /**
   * Load latest log entry.
   */
  public function loadLatestLogEntries($jobs, $log_types) {
    if (Database::getConnection()
      ->databaseType() !== 'mysql') {
      return parent::loadLatestLogEntries($jobs, $log_types);
    }
    $subquery = db_select('ultimate_cron_log', 'l3')
      ->fields('l3', array(
      'name',
      'log_type',
    ))
      ->groupBy('name')
      ->groupBy('log_type');
    $subquery
      ->addExpression('MAX(l3.start_time)', 'start_time');
    $query = db_select('ultimate_cron_log', 'l1')
      ->fields('l1');
    $query
      ->join($subquery, 'l2', 'l1.name = l2.name AND l1.start_time = l2.start_time AND l1.log_type = l2.log_type');
    $query
      ->condition('l2.log_type', $log_types, 'IN');
    $result = $query
      ->execute();
    $log_entries = array();
    while ($object = $result
      ->fetchObject()) {
      if (isset($jobs[$object->name])) {
        $log_entries[$object->name] = new $this->log_entry_class($object->name, $this);
        $log_entries[$object->name]
          ->setData((array) $object);
      }
    }
    foreach ($jobs as $name => $job) {
      if (!isset($log_entries[$name])) {
        $log_entries[$name] = new $this->log_entry_class($name, $this);
      }
    }
    return $log_entries;
  }

  /**
   * Get log entries.
   */
  public function getLogEntries($name, $log_types, $limit = 10) {
    $result = db_select('ultimate_cron_log', 'l')
      ->fields('l')
      ->extend('PagerDefault')
      ->condition('l.name', $name)
      ->condition('l.log_type', $log_types, 'IN')
      ->limit($limit)
      ->orderBy('l.start_time', 'DESC')
      ->execute();
    $log_entries = array();
    while ($object = $result
      ->fetchObject($this->log_entry_class, array(
      $name,
      $this,
    ))) {
      $log_entries[$object->lid] = $object;
    }
    return $log_entries;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
UltimateCronDatabaseLogger::$log_entry_class public property Overrides UltimateCronLogger::$log_entry_class
UltimateCronDatabaseLogger::$options public property
UltimateCronDatabaseLogger::cleanup public function Cleanup logs.
UltimateCronDatabaseLogger::cleanupJob public function Cleanup logs for a single job.
UltimateCronDatabaseLogger::defaultSettings public function Default settings. Overrides UltimateCronPlugin::defaultSettings
UltimateCronDatabaseLogger::getLogEntries public function Get log entries. Overrides UltimateCronLogger::getLogEntries
UltimateCronDatabaseLogger::load public function Load log entry. Overrides UltimateCronLogger::load
UltimateCronDatabaseLogger::loadLatestLogEntries public function Load latest log entry. Overrides UltimateCronLogger::loadLatestLogEntries
UltimateCronDatabaseLogger::settingsForm public function Settings form. Overrides UltimateCronPlugin::settingsForm
UltimateCronDatabaseLogger::settingsFormSubmit public function Submit handler. Overrides UltimateCronPlugin::settingsFormSubmit
UltimateCronDatabaseLogger::settingsLabel public function Label for setting. Overrides UltimateCronPlugin::settingsLabel
UltimateCronDatabaseLogger::__construct public function Constructor. Overrides UltimateCronPlugin::__construct
UltimateCronLogger::$log_entries public static property
UltimateCronLogger::catchMessages public function Begin capturing messages.
UltimateCronLogger::catchMessagesShutdown public function PHP shutdown function callback.
UltimateCronLogger::catchMessagesShutdownWrapper public static function Shutdown handler wrapper for catching messages.
UltimateCronLogger::create public function Create a new log entry.
UltimateCronLogger::factoryLogEntry public function Factory method for creating a new unsaved log entry object.
UltimateCronLogger::hook_watchdog final public static function Invoke loggers watchdog hooks.
UltimateCronLogger::log final public static function Log to ultimate cron logs only.
UltimateCronLogger::unCatchMessages public function End message capturing.
UltimateCronPlugin::$description public property
UltimateCronPlugin::$globalOptions public static property
UltimateCronPlugin::$instances public static property
UltimateCronPlugin::$multiple public static property 1
UltimateCronPlugin::$name public property
UltimateCronPlugin::$plugin public property
UltimateCronPlugin::$settings public property
UltimateCronPlugin::$title public property
UltimateCronPlugin::$weight public property 1
UltimateCronPlugin::build_operations_alter public function Allow plugins to alter the allowed operations for a job. 2
UltimateCronPlugin::cleanForm public function Clean form of empty fallback values.
UltimateCronPlugin::cronapi public function A hook_cronapi() for plugins. 1
UltimateCronPlugin::cron_alter public function A hook_cron_alter() for plugins. 3
UltimateCronPlugin::cron_post_invoke public function A hook_cron_post_invoke() for plugins.
UltimateCronPlugin::cron_post_launch public function A hook_cron_post_launch() for plugins.
UltimateCronPlugin::cron_post_run public function A hook_cron_post_run() for plugins.
UltimateCronPlugin::cron_post_schedule public function A hook_cron_post_schedule() for plugins. 1
UltimateCronPlugin::cron_pre_invoke public function A hook_cron_pre_invoke() for plugins.
UltimateCronPlugin::cron_pre_launch public function A hook_cron_pre_launch() for plugins.
UltimateCronPlugin::cron_pre_run public function A hook_cron_pre_run() for plugins.
UltimateCronPlugin::cron_pre_schedule public function A hook_cron_pre_schedule() for plugins. 2
UltimateCronPlugin::defaultSettingsForm public static function Default settings form. 1
UltimateCronPlugin::drupal_array_remove_nested_value public function Modified version drupal_array_get_nested_value().
UltimateCronPlugin::factory public static function Singleton factoryLogEntry.
UltimateCronPlugin::fallbackalize public function Process fallback form parameters.
UltimateCronPlugin::formatLabel public function Format label for the plugin. 1
UltimateCronPlugin::formatLabelVerbose public function Format verbose label for the plugin. 1
UltimateCronPlugin::getDefaultSettings public function Get default settings. 1
UltimateCronPlugin::getGlobalOption public static function Get global plugin option.
UltimateCronPlugin::getGlobalOptions public static function Get all global plugin options.
UltimateCronPlugin::hook_cron_alter final public static function Invoke hook_cron_alter() on plugins.
UltimateCronPlugin::hook_cron_post_invoke final public static function Invoke hook_cron_post_invoke() on plugins.
UltimateCronPlugin::hook_cron_post_launch final public static function Invoke hook_cron_post_launch() on plugins.
UltimateCronPlugin::hook_cron_post_run final public static function Invoke hook_cron_post_run() on plugins.
UltimateCronPlugin::hook_cron_post_schedule final public static function Invoke hook_cron_post_schedule() on plugins.
UltimateCronPlugin::hook_cron_pre_invoke final public static function Invoke hook_cron_pre_invoke() on plugins.
UltimateCronPlugin::hook_cron_pre_launch final public static function Invoke hook_cron_pre_launch() on plugins.
UltimateCronPlugin::hook_cron_pre_run final public static function Invoke hook_cron_pre_run() on plugins.
UltimateCronPlugin::hook_cron_pre_schedule final public static function Invoke hook_cron_pre_schedule() on plugins.
UltimateCronPlugin::isValid public function Default plugin valid for all jobs. 2
UltimateCronPlugin::jobSettingsForm public static function Job settings form. 1
UltimateCronPlugin::jobSettingsFormSubmit public static function Job settings form submit handler. 1
UltimateCronPlugin::jobSettingsFormValidate public static function Job settings form validate handler. 1
UltimateCronPlugin::setGlobalOption public static function Set global plugin option.
UltimateCronPlugin::setSettings public function Save settings to db.
UltimateCronPlugin::settingsFormValidate public function Settings form validate handler. 1
UltimateCronPlugin::signal public function Signal page for plugins. 2
UltimateCronPlugin::unsetGlobalOption public static function Remove a global plugin option.
UltimateCronPlugin::unsetGlobalOptions public static function Remove all global plugin options.