first commit
This commit is contained in:
@@ -0,0 +1,464 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Controller;
|
||||
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Component\Utility\Xss;
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Core\Controller\ControllerBase;
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Datetime\DateFormatterInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Form\FormBuilderInterface;
|
||||
use Drupal\Core\Logger\RfcLogLevel;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\user\Entity\User;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Drupal\Core\Link;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
/**
|
||||
* Returns responses for dblog routes.
|
||||
*/
|
||||
class DbLogController extends ControllerBase {
|
||||
|
||||
/**
|
||||
* The database service.
|
||||
*
|
||||
* @var \Drupal\Core\Database\Connection
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The module handler service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* The date formatter service.
|
||||
*
|
||||
* @var \Drupal\Core\Datetime\DateFormatterInterface
|
||||
*/
|
||||
protected $dateFormatter;
|
||||
|
||||
/**
|
||||
* The form builder service.
|
||||
*
|
||||
* @var \Drupal\Core\Form\FormBuilderInterface
|
||||
*/
|
||||
protected $formBuilder;
|
||||
|
||||
/**
|
||||
* The user storage.
|
||||
*
|
||||
* @var \Drupal\user\UserStorageInterface
|
||||
*/
|
||||
protected $userStorage;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('database'),
|
||||
$container->get('module_handler'),
|
||||
$container->get('date.formatter'),
|
||||
$container->get('form_builder')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a DbLogController object.
|
||||
*
|
||||
* @param \Drupal\Core\Database\Connection $database
|
||||
* A database connection.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* A module handler.
|
||||
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
|
||||
* The date formatter service.
|
||||
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
|
||||
* The form builder service.
|
||||
*/
|
||||
public function __construct(Connection $database, ModuleHandlerInterface $module_handler, DateFormatterInterface $date_formatter, FormBuilderInterface $form_builder) {
|
||||
$this->database = $database;
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->dateFormatter = $date_formatter;
|
||||
$this->formBuilder = $form_builder;
|
||||
$this->userStorage = $this->entityTypeManager()->getStorage('user');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of log level classes.
|
||||
*
|
||||
* @return array
|
||||
* An array of log level classes.
|
||||
*/
|
||||
public static function getLogLevelClassMap() {
|
||||
return [
|
||||
RfcLogLevel::DEBUG => 'dblog-debug',
|
||||
RfcLogLevel::INFO => 'dblog-info',
|
||||
RfcLogLevel::NOTICE => 'dblog-notice',
|
||||
RfcLogLevel::WARNING => 'dblog-warning',
|
||||
RfcLogLevel::ERROR => 'dblog-error',
|
||||
RfcLogLevel::CRITICAL => 'dblog-critical',
|
||||
RfcLogLevel::ALERT => 'dblog-alert',
|
||||
RfcLogLevel::EMERGENCY => 'dblog-emergency',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a listing of database log messages.
|
||||
*
|
||||
* Messages are truncated at 56 chars.
|
||||
* Full-length messages can be viewed on the message details page.
|
||||
*
|
||||
* @return array
|
||||
* A render array as expected by
|
||||
* \Drupal\Core\Render\RendererInterface::render().
|
||||
*
|
||||
* @see Drupal\dblog\Form\DblogClearLogConfirmForm
|
||||
* @see Drupal\dblog\Controller\DbLogController::eventDetails()
|
||||
*/
|
||||
public function overview() {
|
||||
|
||||
$filter = $this->buildFilterQuery();
|
||||
$rows = [];
|
||||
|
||||
$classes = static::getLogLevelClassMap();
|
||||
|
||||
$this->moduleHandler->loadInclude('dblog', 'admin.inc');
|
||||
|
||||
$build['dblog_filter_form'] = $this->formBuilder->getForm('Drupal\dblog\Form\DblogFilterForm');
|
||||
|
||||
$header = [
|
||||
// Icon column.
|
||||
'',
|
||||
[
|
||||
'data' => $this->t('Type'),
|
||||
'field' => 'w.type',
|
||||
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
|
||||
],
|
||||
[
|
||||
'data' => $this->t('Date'),
|
||||
'field' => 'w.wid',
|
||||
'sort' => 'desc',
|
||||
'class' => [RESPONSIVE_PRIORITY_LOW],
|
||||
],
|
||||
$this->t('Message'),
|
||||
[
|
||||
'data' => $this->t('User'),
|
||||
'field' => 'ufd.name',
|
||||
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
|
||||
],
|
||||
[
|
||||
'data' => $this->t('Operations'),
|
||||
'class' => [RESPONSIVE_PRIORITY_LOW],
|
||||
],
|
||||
];
|
||||
|
||||
$query = $this->database->select('watchdog', 'w')
|
||||
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
|
||||
->extend('\Drupal\Core\Database\Query\TableSortExtender');
|
||||
$query->fields('w', [
|
||||
'wid',
|
||||
'uid',
|
||||
'severity',
|
||||
'type',
|
||||
'timestamp',
|
||||
'message',
|
||||
'variables',
|
||||
'link',
|
||||
]);
|
||||
$query->leftJoin('users_field_data', 'ufd', 'w.uid = ufd.uid');
|
||||
|
||||
if (!empty($filter['where'])) {
|
||||
$query->where($filter['where'], $filter['args']);
|
||||
}
|
||||
$result = $query
|
||||
->limit(50)
|
||||
->orderByHeader($header)
|
||||
->execute();
|
||||
|
||||
foreach ($result as $dblog) {
|
||||
$message = $this->formatMessage($dblog);
|
||||
if ($message && isset($dblog->wid)) {
|
||||
$title = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 256, TRUE, TRUE);
|
||||
$log_text = Unicode::truncate($title, 56, TRUE, TRUE);
|
||||
// The link generator will escape any unsafe HTML entities in the final
|
||||
// text.
|
||||
$message = Link::fromTextAndUrl($log_text, new Url('dblog.event', ['event_id' => $dblog->wid], [
|
||||
'attributes' => [
|
||||
// Provide a title for the link for useful hover hints. The
|
||||
// Attribute object will escape any unsafe HTML entities in the
|
||||
// final text.
|
||||
'title' => $title,
|
||||
],
|
||||
]))->toString();
|
||||
}
|
||||
$username = [
|
||||
'#theme' => 'username',
|
||||
'#account' => $this->userStorage->load($dblog->uid),
|
||||
];
|
||||
$rows[] = [
|
||||
'data' => [
|
||||
// Cells.
|
||||
['class' => ['icon']],
|
||||
$this->t($dblog->type),
|
||||
$this->dateFormatter->format($dblog->timestamp, 'short'),
|
||||
$message,
|
||||
['data' => $username],
|
||||
['data' => ['#markup' => $dblog->link]],
|
||||
],
|
||||
// Attributes for table row.
|
||||
'class' => [Html::getClass('dblog-' . $dblog->type), $classes[$dblog->severity]],
|
||||
];
|
||||
}
|
||||
|
||||
$build['dblog_table'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => $header,
|
||||
'#rows' => $rows,
|
||||
'#attributes' => ['id' => 'admin-dblog', 'class' => ['admin-dblog']],
|
||||
'#empty' => $this->t('No log messages available.'),
|
||||
'#attached' => [
|
||||
'library' => ['dblog/drupal.dblog'],
|
||||
],
|
||||
];
|
||||
$build['dblog_pager'] = ['#type' => 'pager'];
|
||||
|
||||
return $build;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays details about a specific database log message.
|
||||
*
|
||||
* @param int $event_id
|
||||
* Unique ID of the database log message.
|
||||
*
|
||||
* @return array
|
||||
* If the ID is located in the Database Logging table, a build array in the
|
||||
* format expected by \Drupal\Core\Render\RendererInterface::render().
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
|
||||
* If no event found for the given ID.
|
||||
*/
|
||||
public function eventDetails($event_id) {
|
||||
$dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [':id' => $event_id])->fetchObject();
|
||||
|
||||
if (empty($dblog)) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
$build = [];
|
||||
$severity = RfcLogLevel::getLevels();
|
||||
$message = $this->formatMessage($dblog);
|
||||
$username = [
|
||||
'#theme' => 'username',
|
||||
'#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser(),
|
||||
];
|
||||
$rows = [
|
||||
[
|
||||
['data' => $this->t('Type'), 'header' => TRUE],
|
||||
$this->t($dblog->type),
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Date'), 'header' => TRUE],
|
||||
$this->dateFormatter->format($dblog->timestamp, 'long'),
|
||||
],
|
||||
[
|
||||
['data' => $this->t('User'), 'header' => TRUE],
|
||||
['data' => $username],
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Location'), 'header' => TRUE],
|
||||
$this->createLink($dblog->location),
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Referrer'), 'header' => TRUE],
|
||||
$this->createLink($dblog->referer),
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Message'), 'header' => TRUE],
|
||||
$message,
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Severity'), 'header' => TRUE],
|
||||
$severity[$dblog->severity],
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Hostname'), 'header' => TRUE],
|
||||
$dblog->hostname,
|
||||
],
|
||||
[
|
||||
['data' => $this->t('Operations'), 'header' => TRUE],
|
||||
['data' => ['#markup' => $dblog->link]],
|
||||
],
|
||||
];
|
||||
$build['dblog_table'] = [
|
||||
'#type' => 'table',
|
||||
'#rows' => $rows,
|
||||
'#attributes' => ['class' => ['dblog-event']],
|
||||
'#attached' => [
|
||||
'library' => ['dblog/drupal.dblog'],
|
||||
],
|
||||
];
|
||||
|
||||
return $build;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a query for database log administration filters based on session.
|
||||
*
|
||||
* @return array|null
|
||||
* An associative array with keys 'where' and 'args' or NULL if there were
|
||||
* no filters set.
|
||||
*/
|
||||
protected function buildFilterQuery() {
|
||||
if (empty($_SESSION['dblog_overview_filter'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->moduleHandler->loadInclude('dblog', 'admin.inc');
|
||||
|
||||
$filters = dblog_filters();
|
||||
|
||||
// Build query.
|
||||
$where = $args = [];
|
||||
foreach ($_SESSION['dblog_overview_filter'] as $key => $filter) {
|
||||
$filter_where = [];
|
||||
foreach ($filter as $value) {
|
||||
$filter_where[] = $filters[$key]['where'];
|
||||
$args[] = $value;
|
||||
}
|
||||
if (!empty($filter_where)) {
|
||||
$where[] = '(' . implode(' OR ', $filter_where) . ')';
|
||||
}
|
||||
}
|
||||
$where = !empty($where) ? implode(' AND ', $where) : '';
|
||||
|
||||
return [
|
||||
'where' => $where,
|
||||
'args' => $args,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a database log message.
|
||||
*
|
||||
* @param object $row
|
||||
* The record from the watchdog table. The object properties are: wid, uid,
|
||||
* severity, type, timestamp, message, variables, link, name.
|
||||
*
|
||||
* @return string|\Drupal\Core\StringTranslation\TranslatableMarkup|false
|
||||
* The formatted log message or FALSE if the message or variables properties
|
||||
* are not set.
|
||||
*/
|
||||
public function formatMessage($row) {
|
||||
// Check for required properties.
|
||||
if (isset($row->message, $row->variables)) {
|
||||
$variables = @unserialize($row->variables);
|
||||
// Messages without variables or user specified text.
|
||||
if ($variables === NULL) {
|
||||
$message = Xss::filterAdmin($row->message);
|
||||
}
|
||||
elseif (!is_array($variables)) {
|
||||
$message = $this->t('Log data is corrupted and cannot be unserialized: @message', ['@message' => Xss::filterAdmin($row->message)]);
|
||||
}
|
||||
// Message to translate with injected variables.
|
||||
else {
|
||||
// Ensure backtrace strings are properly formatted.
|
||||
if (isset($variables['@backtrace_string'])) {
|
||||
$variables['@backtrace_string'] = new FormattableMarkup(
|
||||
'<pre class="backtrace">@backtrace_string</pre>', $variables
|
||||
);
|
||||
}
|
||||
$message = $this->t(Xss::filterAdmin($row->message), $variables);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$message = FALSE;
|
||||
}
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Link object if the provided URI is valid.
|
||||
*
|
||||
* @param string|null $uri
|
||||
* The uri string to convert into link if valid.
|
||||
*
|
||||
* @return \Drupal\Core\Link|string|null
|
||||
* Return a Link object if the uri can be converted as a link. In case of
|
||||
* empty uri or invalid, fallback to the provided $uri.
|
||||
*/
|
||||
protected function createLink($uri) {
|
||||
if (UrlHelper::isValid($uri, TRUE)) {
|
||||
return new Link($uri, Url::fromUri($uri));
|
||||
}
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the most frequent log messages of a given event type.
|
||||
*
|
||||
* Messages are not truncated on this page because events detailed herein do
|
||||
* not have links to a detailed view.
|
||||
*
|
||||
* @param string $type
|
||||
* Type of database log events to display (e.g., 'search').
|
||||
*
|
||||
* @return array
|
||||
* A build array in the format expected by
|
||||
* \Drupal\Core\Render\RendererInterface::render().
|
||||
*/
|
||||
public function topLogMessages($type) {
|
||||
$header = [
|
||||
['data' => $this->t('Count'), 'field' => 'count', 'sort' => 'desc'],
|
||||
['data' => $this->t('Message'), 'field' => 'message'],
|
||||
];
|
||||
|
||||
$count_query = $this->database->select('watchdog');
|
||||
$count_query->addExpression('COUNT(DISTINCT(message))');
|
||||
$count_query->condition('type', $type);
|
||||
|
||||
$query = $this->database->select('watchdog', 'w')
|
||||
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
|
||||
->extend('\Drupal\Core\Database\Query\TableSortExtender');
|
||||
$query->addExpression('COUNT(wid)', 'count');
|
||||
$query = $query
|
||||
->fields('w', ['message', 'variables'])
|
||||
->condition('w.type', $type)
|
||||
->groupBy('message')
|
||||
->groupBy('variables')
|
||||
->limit(30)
|
||||
->orderByHeader($header);
|
||||
$query->setCountQuery($count_query);
|
||||
$result = $query->execute();
|
||||
|
||||
$rows = [];
|
||||
foreach ($result as $dblog) {
|
||||
if ($message = $this->formatMessage($dblog)) {
|
||||
$rows[] = [$dblog->count, $message];
|
||||
}
|
||||
}
|
||||
|
||||
$build['dblog_top_table'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => $header,
|
||||
'#rows' => $rows,
|
||||
'#empty' => $this->t('No log messages available.'),
|
||||
'#attached' => [
|
||||
'library' => ['dblog/drupal.dblog'],
|
||||
],
|
||||
];
|
||||
$build['dblog_top_pager'] = ['#type' => 'pager'];
|
||||
|
||||
return $build;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Form;
|
||||
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Form\ConfirmFormBase;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides a confirmation form before clearing out the logs.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class DblogClearLogConfirmForm extends ConfirmFormBase {
|
||||
|
||||
/**
|
||||
* The database connection.
|
||||
*
|
||||
* @var \Drupal\Core\Database\Connection
|
||||
*/
|
||||
protected $connection;
|
||||
|
||||
/**
|
||||
* Constructs a new DblogClearLogConfirmForm.
|
||||
*
|
||||
* @param \Drupal\Core\Database\Connection $connection
|
||||
* The database connection.
|
||||
*/
|
||||
public function __construct(Connection $connection) {
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('database')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'dblog_confirm';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getQuestion() {
|
||||
return $this->t('Are you sure you want to delete the recent logs?');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getCancelUrl() {
|
||||
return new Url('dblog.overview');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$_SESSION['dblog_overview_filter'] = [];
|
||||
$this->connection->truncate('watchdog')->execute();
|
||||
$this->messenger()->addStatus($this->t('Database log cleared.'));
|
||||
$form_state->setRedirectUrl($this->getCancelUrl());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Form;
|
||||
|
||||
use Drupal\Core\Form\FormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
|
||||
/**
|
||||
* Provides the database logging filter form.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class DblogFilterForm extends FormBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'dblog_filter_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$filters = dblog_filters();
|
||||
|
||||
$form['filters'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Filter log messages'),
|
||||
'#open' => TRUE,
|
||||
];
|
||||
foreach ($filters as $key => $filter) {
|
||||
$form['filters']['status'][$key] = [
|
||||
'#title' => $filter['title'],
|
||||
'#type' => 'select',
|
||||
'#multiple' => TRUE,
|
||||
'#size' => 8,
|
||||
'#options' => $filter['options'],
|
||||
];
|
||||
if (!empty($_SESSION['dblog_overview_filter'][$key])) {
|
||||
$form['filters']['status'][$key]['#default_value'] = $_SESSION['dblog_overview_filter'][$key];
|
||||
}
|
||||
}
|
||||
|
||||
$form['filters']['actions'] = [
|
||||
'#type' => 'actions',
|
||||
'#attributes' => ['class' => ['container-inline']],
|
||||
];
|
||||
$form['filters']['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Filter'),
|
||||
];
|
||||
if (!empty($_SESSION['dblog_overview_filter'])) {
|
||||
$form['filters']['actions']['reset'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Reset'),
|
||||
'#limit_validation_errors' => [],
|
||||
'#submit' => ['::resetForm'],
|
||||
];
|
||||
}
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
if ($form_state->isValueEmpty('type') && $form_state->isValueEmpty('severity')) {
|
||||
$form_state->setErrorByName('type', $this->t('You must select something to filter by.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$filters = dblog_filters();
|
||||
foreach ($filters as $name => $filter) {
|
||||
if ($form_state->hasValue($name)) {
|
||||
$_SESSION['dblog_overview_filter'][$name] = $form_state->getValue($name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the filter form.
|
||||
*
|
||||
* @param array $form
|
||||
* An associative array containing the structure of the form.
|
||||
* @param \Drupal\Core\Form\FormStateInterface $form_state
|
||||
* The current state of the form.
|
||||
*/
|
||||
public function resetForm(array &$form, FormStateInterface $form_state) {
|
||||
$_SESSION['dblog_overview_filter'] = [];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Logger;
|
||||
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\Core\Database\DatabaseException;
|
||||
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
|
||||
use Drupal\Core\Logger\LogMessageParserInterface;
|
||||
use Drupal\Core\Logger\RfcLoggerTrait;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Logs events in the watchdog database table.
|
||||
*/
|
||||
class DbLog implements LoggerInterface {
|
||||
use RfcLoggerTrait;
|
||||
use DependencySerializationTrait;
|
||||
|
||||
/**
|
||||
* The dedicated database connection target to use for log entries.
|
||||
*/
|
||||
const DEDICATED_DBLOG_CONNECTION_TARGET = 'dedicated_dblog';
|
||||
|
||||
/**
|
||||
* The database connection object.
|
||||
*
|
||||
* @var \Drupal\Core\Database\Connection
|
||||
*/
|
||||
protected $connection;
|
||||
|
||||
/**
|
||||
* The message's placeholders parser.
|
||||
*
|
||||
* @var \Drupal\Core\Logger\LogMessageParserInterface
|
||||
*/
|
||||
protected $parser;
|
||||
|
||||
/**
|
||||
* Constructs a DbLog object.
|
||||
*
|
||||
* @param \Drupal\Core\Database\Connection $connection
|
||||
* The database connection object.
|
||||
* @param \Drupal\Core\Logger\LogMessageParserInterface $parser
|
||||
* The parser to use when extracting message variables.
|
||||
*/
|
||||
public function __construct(Connection $connection, LogMessageParserInterface $parser) {
|
||||
$this->connection = $connection;
|
||||
$this->parser = $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function log($level, $message, array $context = []) {
|
||||
// Remove any backtraces since they may contain an unserializable variable.
|
||||
unset($context['backtrace']);
|
||||
|
||||
// Convert PSR3-style messages to \Drupal\Component\Render\FormattableMarkup
|
||||
// style, so they can be translated too in runtime.
|
||||
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
|
||||
|
||||
try {
|
||||
$this->connection
|
||||
->insert('watchdog')
|
||||
->fields([
|
||||
'uid' => $context['uid'],
|
||||
'type' => mb_substr($context['channel'], 0, 64),
|
||||
'message' => $message,
|
||||
'variables' => serialize($message_placeholders),
|
||||
'severity' => $level,
|
||||
'link' => $context['link'],
|
||||
'location' => $context['request_uri'],
|
||||
'referer' => $context['referer'],
|
||||
'hostname' => mb_substr($context['ip'], 0, 128),
|
||||
'timestamp' => $context['timestamp'],
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
// When running Drupal on MySQL or MariaDB you can run into several errors
|
||||
// that corrupt the database connection. Some examples for these kind of
|
||||
// errors on the database layer are "1100 - Table 'xyz' was not locked
|
||||
// with LOCK TABLES" and "1153 - Got a packet bigger than
|
||||
// 'max_allowed_packet' bytes". If such an error happens, the MySQL server
|
||||
// invalidates the connection and answers all further requests in this
|
||||
// connection with "2006 - MySQL server had gone away". In that case the
|
||||
// insert statement above results in a database exception. To ensure that
|
||||
// the causal error is written to the log we try once to open a dedicated
|
||||
// connection and write again.
|
||||
if (
|
||||
// Only handle database related exceptions.
|
||||
($e instanceof DatabaseException || $e instanceof \PDOException) &&
|
||||
// Avoid an endless loop of re-write attempts.
|
||||
$this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET
|
||||
) {
|
||||
// Open a dedicated connection for logging.
|
||||
$key = $this->connection->getKey();
|
||||
$info = Database::getConnectionInfo($key);
|
||||
Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']);
|
||||
$this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key);
|
||||
// Now try once to log the error again.
|
||||
$this->log($level, $message, $context);
|
||||
}
|
||||
else {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Plugin\rest\resource;
|
||||
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\rest\Plugin\ResourceBase;
|
||||
use Drupal\rest\ResourceResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
/**
|
||||
* Provides a resource for database watchdog log entries.
|
||||
*
|
||||
* @RestResource(
|
||||
* id = "dblog",
|
||||
* label = @Translation("Watchdog database log"),
|
||||
* uri_paths = {
|
||||
* "canonical" = "/dblog/{id}"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class DBLogResource extends ResourceBase {
|
||||
|
||||
/**
|
||||
* Responds to GET requests.
|
||||
*
|
||||
* Returns a watchdog log entry for the specified ID.
|
||||
*
|
||||
* @param int $id
|
||||
* The ID of the watchdog log entry.
|
||||
*
|
||||
* @return \Drupal\rest\ResourceResponse
|
||||
* The response containing the log entry.
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
|
||||
* Thrown when the log entry was not found.
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
|
||||
* Thrown when no log entry was provided.
|
||||
*/
|
||||
public function get($id = NULL) {
|
||||
if ($id) {
|
||||
$record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id])
|
||||
->fetchAssoc();
|
||||
if (!empty($record)) {
|
||||
return new ResourceResponse($record);
|
||||
}
|
||||
|
||||
throw new NotFoundHttpException("Log entry with ID '$id' was not found");
|
||||
}
|
||||
|
||||
throw new BadRequestHttpException('No log entry ID was provided');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Plugin\views\field;
|
||||
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\views\Plugin\views\field\FieldPluginBase;
|
||||
use Drupal\views\ResultRow;
|
||||
use Drupal\views\ViewExecutable;
|
||||
use Drupal\views\Plugin\views\display\DisplayPluginBase;
|
||||
|
||||
/**
|
||||
* Provides a field handler that renders a log event with replaced variables.
|
||||
*
|
||||
* @ingroup views_field_handlers
|
||||
*
|
||||
* @ViewsField("dblog_message")
|
||||
*/
|
||||
class DblogMessage extends FieldPluginBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
|
||||
parent::init($view, $display, $options);
|
||||
|
||||
if ($this->options['replace_variables']) {
|
||||
$this->additional_fields['variables'] = 'variables';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function defineOptions() {
|
||||
$options = parent::defineOptions();
|
||||
$options['replace_variables'] = ['default' => TRUE];
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
|
||||
parent::buildOptionsForm($form, $form_state);
|
||||
|
||||
$form['replace_variables'] = [
|
||||
'#title' => $this->t('Replace variables'),
|
||||
'#type' => 'checkbox',
|
||||
'#default_value' => $this->options['replace_variables'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function render(ResultRow $values) {
|
||||
$value = $this->getValue($values);
|
||||
|
||||
if ($this->options['replace_variables']) {
|
||||
$variables = unserialize($this->getvalue($values, 'variables'));
|
||||
return new FormattableMarkup($value, (array) $variables);
|
||||
}
|
||||
else {
|
||||
return $this->sanitizeValue($value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Plugin\views\field;
|
||||
|
||||
use Drupal\views\Plugin\views\field\FieldPluginBase;
|
||||
use Drupal\views\ResultRow;
|
||||
|
||||
/**
|
||||
* Provides a field handler that renders operation link markup.
|
||||
*
|
||||
* @ingroup views_field_handlers
|
||||
*
|
||||
* @ViewsField("dblog_operations")
|
||||
*/
|
||||
class DblogOperations extends FieldPluginBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function clickSortable() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function render(ResultRow $values) {
|
||||
$value = $this->getValue($values);
|
||||
return $this->sanitizeValue($value, 'xss_admin');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Plugin\views\filter;
|
||||
|
||||
use Drupal\views\Plugin\views\filter\InOperator;
|
||||
|
||||
/**
|
||||
* Exposes log types to views module.
|
||||
*
|
||||
* @ViewsFilter("dblog_types")
|
||||
*/
|
||||
class DblogTypes extends InOperator {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getValueOptions() {
|
||||
if (!isset($this->valueOptions)) {
|
||||
$this->valueOptions = _dblog_get_message_types();
|
||||
}
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\dblog\Plugin\views\wizard;
|
||||
|
||||
use Drupal\views\Plugin\views\wizard\WizardPluginBase;
|
||||
|
||||
/**
|
||||
* Defines a wizard for the watchdog table.
|
||||
*
|
||||
* @ViewsWizard(
|
||||
* id = "watchdog",
|
||||
* module = "dblog",
|
||||
* base_table = "watchdog",
|
||||
* title = @Translation("Log entries")
|
||||
* )
|
||||
*/
|
||||
class Watchdog extends WizardPluginBase {
|
||||
|
||||
/**
|
||||
* Set the created column.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $createdColumn = 'timestamp';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function defaultDisplayOptions() {
|
||||
$display_options = parent::defaultDisplayOptions();
|
||||
|
||||
// Add permission-based access control.
|
||||
$display_options['access']['type'] = 'perm';
|
||||
$display_options['access']['options']['perm'] = 'access site reports';
|
||||
|
||||
return $display_options;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user