foldershare-8.x-1.2/src/ManageLog.php

src/ManageLog.php
<?php

namespace Drupal\foldershare;

use Drupal\user\Entity\User;

/**
 * Manages logging for the FolderShare module.
 *
 * This class provides static methods to manage logging of activities
 * and errors by this module. Supported operations include:
 * - Posting an activity message to the log.
 * - Posting an error message to the log.
 *
 * This method also provides methods to query configuration settings
 * that enable/disable activity logging.
 *
 * <B>Access control</B>
 * This class's methods do not do access control. The caller should check
 * access as needed by their situation.
 *
 * @ingroup foldershare
 *
 * @see \Drupal\foldershare\Settings
 * @see \Drupal\foldershare\Entity\FolderShare
 */
trait ManageLog {

  /*---------------------------------------------------------------------
   *
   * Configuration.
   *
   *---------------------------------------------------------------------*/

  /**
   * Returns TRUE if the module's activity logging is enabled.
   *
   * When disabled, the module should not post activity messages to the
   * log. Error messages are still posted.
   *
   * @return bool
   *   Returns TRUE if activity logging is enabled.
   *
   * @see \Drupal\foldershare\Settings::getActivityLogEnable()
   */
  public static function isActivityLoggingEnabled() {
    return Settings::getActivityLogEnable();
  }

  /**
   * Returns the module title.
   *
   * The module title is a mixed case name, rather than the lowercase
   * machine name.
   *
   * @return string
   *   The module title.
   */
  private static function getModuleTitle() {
    // Cache the module title since it is unlikely to change.
    static $title = '';
    if ($title === '') {
      $moduleHandler = \Drupal::service('module_handler');
      $title = $moduleHandler->getName(Constants::MODULE);
    }

    return $title;
  }

  /*---------------------------------------------------------------------
   *
   * Logging.
   *
   *---------------------------------------------------------------------*/

  /**
   * Posts an activity message to the log.
   *
   * If the module's activity logging has been disabled, no message is posted.
   * Otherwise a 'notice' message is posted.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::isActivityLoggingEnabled()
   * @see ::log()
   */
  public static function activity(string $message, array $context = []) {
    if (self::isActivityLoggingEnabled() === FALSE) {
      return;
    }

    self::log('notice', $message, $context);
  }

  /**
   * Posts an alert message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function alert(string $message, array $context = []) {
    self::log('alert', $message, $context);
  }

  /**
   * Posts a critical message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function critical(string $message, array $context = []) {
    self::log('critical', $message, $context);
  }

  /**
   * Posts a debug message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function debug(string $message, array $context = []) {
    self::log('debug', $message, $context);
  }

  /**
   * Posts an emergency message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function emergency(string $message, array $context = []) {
    self::log('emergency', $message, $context);
  }

  /**
   * Posts an error message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function error(string $message, array $context = []) {
    self::log('error', $message, $context);
  }

  /**
   * Posts an error message about an exception to the log.
   *
   * The exception's type, message, and stack trace are added to the log.
   *
   * @param \Exception $e
   *   The exception.
   * @param int $uid
   *   (optional, default = (-1) = current user) The user ID of the user
   *   associated with the activity.
   */
  public static function exception(\Exception $e, int $uid = (-1)) {
    if ($e === NULL) {
      return;
    }

    $context = [
      'exception' => $e,
      'uid'       => $uid,
    ];

    self::log('error', '', $context);
  }

  /**
   * Posts an info message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function info(string $message, array $context = []) {
    self::log('info', $message, $context);
  }

  /**
   * Posts a notice message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function notice(string $message, array $context = []) {
    self::log('notice', $message, $context);
  }

  /**
   * Posts a warning message to the log.
   *
   * See log() for a detailed explanation of method arguments.
   *
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) The message context.
   *
   * @see ::log()
   */
  public static function warning(string $message, array $context = []) {
    self::log('warning', $message, $context);
  }

  /**
   * Posts a message to the log.
   *
   * If the message is empty, no message is logged.
   *
   * The severity level is expected to be one of the standard values:
   *   - "alert".
   *   - "critical".
   *   - "debug".
   *   - "emergency".
   *   - "error".
   *   - "info".
   *   - "notice".
   *   - "warning".
   *
   * If the severity level is empty, it defaults to 'notice'.
   *
   * If the message includes embedded carriage returns, they are replaced
   * with an HTML "<BR>" and carriage return so that the lines format better
   * on the message's detail page.
   *
   * Messages may contain variables of the form @name or %name that will be
   * replaced by their corresponding values for keys in the $context
   * associative array.
   *
   * The $context array may include substitution variables along with
   * special values processed by this method:
   *
   *   - "exception": An \Exception object. When present, the exception's
   *     type, message, and backtrace are appended to the given message.
   *
   *   - "entity": An entity, such as a FolderShare entity. When present,
   *     a link to the entity's page is added to the context as a "link"
   *     value that the logging system automatically adds into the
   *     "Operation" column of the standard log message page.
   *
   *   - "uid": The user performing the operation that led to the log
   *     message. When present, the message's user is set and the logging
   *     system automatically adds their name and a lnk into the "User"
   *     column of the standard log message page.
   *
   * The $context array may include additional special values processed by
   * the logging system:
   *
   *   - "channel": The message channel or type. This is automatically set
   *     to the module title, but any value in "channel" overrides this
   *     title.
   *
   *   - "timestamp": The log message time. This is automatically set to
   *     the current time.
   *
   * Additional values are automatically set by the logging system:
   *
   *   - "ip": The request IP address.
   *
   *   - "referer": The request referer.
   *
   *   - 'request_uri': The request URI.
   *
   * @param string $level
   *   The log level.
   * @param string $message
   *   The message to be logged.
   * @param array $context
   *   (optional, default = []) An associative array that provides mappings
   *   from keys to values.
   */
  public static function log(
    string $level,
    string $message,
    array $context = []) {

    // Default to a low-priority message.
    if (empty($level) === TRUE) {
      $level = 'notice';
    }

    // If an exception is given, create message text including the
    // exception type, exception message, and stack trace.
    $em = '';
    if (isset($context['exception']) === TRUE &&
        $context['exception'] !== NULL &&
        $context['exception'] instanceof \Exception === TRUE) {
      $e = $context['exception'];
      unset($context['exception']);

      $context['%exceptionType'] = get_class($e);
      $context['%exceptionMessage'] = $e->getMessage();
      $context['@exceptionBacktrace'] = $e->getTraceAsString();
      $em = "%exceptionType: %exceptionMessage <BR>\n<PRE>@exceptionBacktrace</PRE>";
    }

    // If there is neither a given message or an exception, then do nothing.
    if (empty($message) === TRUE && empty($em) === TRUE) {
      return;
    }

    // Replace carriage returns with line breaks for better formatting
    // on a log detail page.
    $m = mb_ereg_replace("\n", " <BR>\n", $message);
    if ($m === FALSE) {
      $m = $message;
    }

    // Add the exception message, if any.
    $m .= $em;

    // If an entity is given, use it for the log message link.
    if (isset($context['entity']) === TRUE &&
        isset($context['link']) === FALSE &&
        $context['entity'] !== NULL &&
        method_exists($context['entity'], 'toLink') === TRUE) {
      $entity = $context['entity'];
      unset($context['entity']);

      $context['link'] = $entity->toLink('View')->toString();

      $m .= " <BR>\nPath: @path";
      $context['@path'] = $entity->getPath();
    }

    $logger = \Drupal::logger(self::getModuleTitle());

    // Set the current user for purposes of logging.
    if (isset($context['uid']) === TRUE &&
        (int) $context['uid'] >= 0) {
      $currentUser = \Drupal::currentUser();
      if ((int) $context['uid'] === (int) $currentUser->id()) {
        $logger->setCurrentUser($currentUser);
      }
      else {
        $logger->setCurrentUser(User::load($context['uid']));
      }
    }

    $logger->log($level, $m, $context);
  }

  /*---------------------------------------------------------------------
   *
   * Standard messages.
   *
   *---------------------------------------------------------------------*/

  /**
   * Logs a standard error message about a missing scheduled task parameter.
   *
   * @param string $taskName
   *   The name of the task reporting the error.
   * @param string $parameterName
   *   The name of the parameter that is missing.
   */
  public static function missingTaskParameter(
    string $taskName,
    string $parameterName) {

    self::error(
      "Programmer error: Missing or bad parameter '@parameterName' for task '@taskName'.",
      [
        '@parameterName' => $parameterName,
        '@taskName'      => $taskName,
      ]);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc