Completed
Push — 15-request_grouping ( 76e174...2ffca1 )
by Frédéric G.
02:55
created

Logger::requestEvents()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 19
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 31
rs 8.8571
1
<?php
2
3
namespace Drupal\mongodb_watchdog;
4
5
use Drupal\Component\Render\MarkupInterface;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Component\Utility\Xss;
8
use Drupal\Core\Config\ConfigFactoryInterface;
9
use Drupal\Core\Logger\LogMessageParserInterface;
10
use MongoDB\Database;
11
use MongoDB\Driver\Exception\InvalidArgumentException;
12
use Psr\Log\AbstractLogger;
13
use Symfony\Component\HttpFoundation\RequestStack;
14
15
/**
16
 * Class Logger is a PSR/3 Logger using a MongoDB data store.
17
 *
18
 * @package Drupal\mongodb_watchdog
19
 */
20
class Logger extends AbstractLogger {
21
  const CONFIG_NAME = 'mongodb_watchdog.settings';
22
23
  const TRACKER_COLLECTION = 'watchdog_tracker';
24
  const TEMPLATE_COLLECTION = 'watchdog';
25
  const EVENT_COLLECTION_PREFIX = 'watchdog_event_';
26
  const EVENT_COLLECTIONS_PATTERN = '^watchdog_event_[[:xdigit:]]{32}$';
27
28
  const LEGACY_TYPE_MAP = [
29
    'typeMap' => [
30
      'array' => 'array',
31
      'document' => 'array',
32
      'root' => 'array',
33
    ],
34
  ];
35
36
  /**
37
   * The logger storage.
38
   *
39
   * @var \MongoDB\Database
40
   */
41
  protected $database;
42
43
  /**
44
   * The limit for the capped event collections.
45
   *
46
   * @var int
47
   */
48
  protected $items;
49
50
  /**
51
   * The minimum logging level.
52
   *
53
   * @var int
54
   */
55
  protected $limit;
56
57
  /**
58
   * The message's placeholders parser.
59
   *
60
   * @var \Drupal\Core\Logger\LogMessageParserInterface
61
   */
62
  protected $parser;
63
64
  /**
65
   * An array of templates already used in this request.
66
   *
67
   * Used only with request tracking enabled.
68
   *
69
   * @var string[]
70
   */
71
  protected $templates = [];
72
73
  /**
74
   * A sequence number for log events during a request.
75
   *
76
   * @var int
77
   */
78
  protected $sequence = 0;
79
80
  /**
81
   * Logger constructor.
82
   *
83
   * @param \MongoDB\Database $database
84
   *   The database object.
85
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
86
   *   The parser to use when extracting message variables.
87
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
88
   *   The core config_factory service.
89
   * @param \Symfony\Component\HttpFoundation\RequestStack $stack
90
   *   The core request_stack service.
91
   */
92
  public function __construct(Database $database, LogMessageParserInterface $parser, ConfigFactoryInterface $config_factory, RequestStack $stack) {
93
    $this->database = $database;
94
    $this->parser = $parser;
95
    $this->requestStack = $stack;
96
97
    $config = $config_factory->get(static::CONFIG_NAME);
98
    $this->limit = $config->get('limit');
99
    $this->items = $config->get('items');
100
    $this->requestTracking = $config->get('request_tracking');
101
  }
102
103
  /**
104
   * Fill in the log_entry function, file, and line.
105
   *
106
   * @param array $log_entry
107
   *   An event information to be logger.
108
   * @param array $backtrace
109
   *   A call stack.
110
   */
111
  protected function enhanceLogEntry(array &$log_entry, array $backtrace) {
112
    // Create list of functions to ignore in backtrace.
113
    static $ignored = array(
114
      'call_user_func_array' => 1,
115
      '_drupal_log_error' => 1,
116
      '_drupal_error_handler' => 1,
117
      '_drupal_error_handler_real' => 1,
118
      'Drupal\mongodb_watchdog\Logger::log' => 1,
119
      'Drupal\Core\Logger\LoggerChannel::log' => 1,
120
      'Drupal\Core\Logger\LoggerChannel::alert' => 1,
121
      'Drupal\Core\Logger\LoggerChannel::critical' => 1,
122
      'Drupal\Core\Logger\LoggerChannel::debug' => 1,
123
      'Drupal\Core\Logger\LoggerChannel::emergency' => 1,
124
      'Drupal\Core\Logger\LoggerChannel::error' => 1,
125
      'Drupal\Core\Logger\LoggerChannel::info' => 1,
126
      'Drupal\Core\Logger\LoggerChannel::notice' => 1,
127
      'Drupal\Core\Logger\LoggerChannel::warning' => 1,
128
    );
129
130
    foreach ($backtrace as $bt) {
131
      if (isset($bt['function'])) {
132
        $function = empty($bt['class']) ? $bt['function'] : $bt['class'] . '::' . $bt['function'];
133
        if (empty($ignored[$function])) {
134
          $log_entry['%function'] = $function;
135
          /* Some part of the stack, like the line or file info, may be missing.
136
           *
137
           * @see http://goo.gl/8s75df
138
           *
139
           * No need to fetch the line using reflection: it would be redundant
140
           * with the name of the function.
141
           */
142
          $log_entry['%line'] = isset($bt['line']) ? $bt['line'] : NULL;
143
          if (empty($bt['file'])) {
144
            $reflected_method = new \ReflectionMethod($function);
145
            $bt['file'] = $reflected_method->getFileName();
146
          }
147
148
          $log_entry['%file'] = $bt['file'];
149
          break;
150
        }
151
        elseif ($bt['function'] == '_drupal_exception_handler') {
152
          $e = $bt['args'][0];
153
          $this->enhanceLogEntry($log_entry, $e->getTrace());
154
        }
155
      }
156
    }
157
  }
158
159
  /**
160
   * {@inheritdoc}
161
   */
162
  public function log($level, $template, array $context = []) {
163
    if ($level > $this->limit) {
164
      return;
165
    }
166
167
    // Convert PSR3-style messages to SafeMarkup::format() style, so they can be
168
    // translated too in runtime.
169
    $message_placeholders = $this->parser->parseMessagePlaceholders($template, $context);
170
171
    // If code location information is all present, as for errors/exceptions,
172
    // then use it to build the message template id.
173
    $type = $context['channel'];
174
    $location_info = [
175
      '%type' => 1,
176
      '@message' => 1,
177
      '%function' => 1,
178
      '%file' => 1,
179
      '%line' => 1,
180
    ];
181
    if (!empty(array_diff_key($location_info, $message_placeholders))) {
182
      $this->enhanceLogEntry($message_placeholders, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10));
183
    }
184
    $file = $message_placeholders['%file'];
185
    $line = $message_placeholders['%line'];
186
    $function = $message_placeholders['%function'];
187
    $key = "${type}:${level}:${file}:${line}:${function}";
188
    $template_id = md5($key);
189
190
    $selector = ['_id' => $template_id];
191
    $update = [
192
      '_id' => $template_id,
193
      'type' => Unicode::substr($context['channel'], 0, 64),
194
      'message' => $template,
195
      'severity' => $level,
196
    ];
197
    $options = ['upsert' => TRUE];
198
    $template_result = $this->database
199
      ->selectCollection(static::TEMPLATE_COLLECTION)
200
      ->replaceOne($selector, $update, $options);
201
    // Only add the template if if has not already been added.
202
    if ($this->requestTracking) {
203
      $request_id = $this->requestStack
204
        ->getCurrentRequest()
205
        ->server
206
        ->get('UNIQUE_ID');
207
208
      if (isset($this->templates[$template_id])) {
209
        $this->templates[$template_id]++;
210
      }
211
      else {
212
        $this->templates[$template_id] = 1;
213
        $selector = ['_id' => $request_id];
214
        $update = ['$addToSet' => ['templates' => $template_id]];
215
        $this->trackerCollection()->updateOne($selector, $update, $options);
216
      }
217
    }
218
219
    $event_collection = $this->eventCollection($template_id);
220
    if ($template_result->getUpsertedCount()) {
221
      // Capped collections are actually size-based, not count-based, so "items"
222
      // is only a maximum, assuming event documents weigh 1kB, but the actual
223
      // number of items stored may be lower if items are heavier.
224
      // We do not use 'autoindexid' for greater speed, because:
225
      // - it does not work on replica sets,
226
      // - it is deprecated in MongoDB 3.2 and going away in 3.4.
227
      $options = [
228
        'capped' => TRUE,
229
        'size' => $this->items * 1024,
230
        'max' => $this->items,
231
      ];
232
      $this->database->createCollection($event_collection->getCollectionName(), $options);
233
    }
234
235
    foreach ($message_placeholders as &$placeholder) {
236
      if ($placeholder instanceof MarkupInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Component\Render\MarkupInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
237
        $placeholder = Xss::filterAdmin($placeholder);
238
      }
239
    }
240
    $event = [
241
      'hostname' => Unicode::substr($context['ip'], 0, 128),
242
      'link' => $context['link'],
243
      'location' => $context['request_uri'],
244
      'referer' => $context['referer'],
245
      'timestamp' => $context['timestamp'],
246
      'user' => ['uid' => $context['uid']],
247
      'variables' => $message_placeholders,
248
    ];
249
    if ($this->requestTracking) {
250
      // Fetch the current request on each event to support subrequest nesting.
251
      $event['requestTracking_id'] = $request_id;
0 ignored issues
show
Bug introduced by
The variable $request_id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
252
      $event['requestTracking_sequence'] = $this->sequence;
253
      $this->sequence++;
254
    }
255
    $event_collection->insertOne($event);
256
  }
257
258
  /**
259
   * List the event collections.
260
   *
261
   * @return \MongoDB\Collection[]
262
   *   The collections with a name matching the event pattern.
263
   */
264
  public function eventCollections() {
265
    echo static::EVENT_COLLECTIONS_PATTERN;
266
    $options = [
267
      'filter' => [
268
        'name' => ['$regex' => static::EVENT_COLLECTIONS_PATTERN],
269
      ],
270
    ];
271
    $result = iterator_to_array($this->database->listCollections($options));
272
    return $result;
273
  }
274
275
  /**
276
   * Return a collection, given its template id.
277
   *
278
   * @param string $template_id
279
   *   The string representation of a template \MongoId.
280
   *
281
   * @return \MongoDB\Collection
282
   *   A collection object for the specified template id.
283
   */
284
  public function eventCollection($template_id) {
285
    $collection_name = static::EVENT_COLLECTION_PREFIX . $template_id;
286
    if (!preg_match('/' . static::EVENT_COLLECTIONS_PATTERN . '/', $collection_name)) {
287
      throw new InvalidArgumentException(t('Invalid watchdog template id `@id`.', [
288
        '@id' => $collection_name,
289
      ]));
290
    }
291
    $collection = $this->database->selectCollection($collection_name);
292
    return $collection;
293
  }
294
295
  /**
296
   * Ensure indexes are set on the collections.
297
   *
298
   * First index is on <line, timestamp> instead of <function, line, timestamp>,
299
   * because we write to this collection a lot, and the smaller index on two
300
   * numbers should be much faster to create than one with a string included.
301
   */
302
  public function ensureIndexes() {
303
    $templates = $this->database->selectCollection(static::TEMPLATE_COLLECTION);
304
    $indexes = [
305
      // Index for adding/updating increments.
306
      [
307
        'name' => 'for-increments',
308
        'key' => ['line' => 1, 'timestamp' => -1],
309
      ],
310
311
      // Index for admin page without filters.
312
      [
313
        'name' => 'admin-no-filters',
314
        'key' => ['timestamp' => -1],
315
      ],
316
317
      // Index for admin page filtering by type.
318
      [
319
        'name' => 'admin-by-type',
320
        'key' => ['type' => 1, 'timestamp' => -1],
321
      ],
322
323
      // Index for admin page filtering by severity.
324
      [
325
        'name' => 'admin-by-severity',
326
        'key' => ['severity' => 1, 'timestamp' => -1],
327
      ],
328
329
      // Index for admin page filtering by type and severity.
330
      [
331
        'name' => 'admin-by-both',
332
        'key' => ['type' => 1, 'severity' => 1, 'timestamp' => -1],
333
      ],
334
    ];
335
    $templates->createIndexes($indexes);
336
  }
337
338
  /**
339
   * Return the events having occurred during a given request.
340
   *
341
   * @param string $unsafe_request_id
342
   *   The raw request_id.
343
   * @return array
0 ignored issues
show
introduced by
Separate the @param and @return sections by a blank line.
Loading history...
344
   *   An array of [template, event] arrays, ordered by occurrence order.
345
   */
346
  public function requestEvents(string $unsafe_request_id) {
0 ignored issues
show
introduced by
Unknown type hint "string" found for $unsafe_request_id
Loading history...
347
    $templates = $this->requestTemplates($unsafe_request_id);
348
    $request_id = "$unsafe_request_id";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $unsafe_request_id instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
349
    $events = [];
350
    $options = [
351
      'typeMap' => [
352
        'array' => 'array',
353
        'document' => 'array',
354
        'root' => '\Drupal\mongodb_watchdog\Event',
355
      ],
356
    ];
357
358
    /**
359
     * @var string $template_id
360
     * @var \Drupal\mongodb_watchdog\EventTemplate $template
361
     */
362
    foreach ($templates as $template_id => $template) {
363
      $event_collection = $this->eventCollection($template_id);
364
      $selector = ['requestTracking_id' => $request_id];
365
      $cursor = $event_collection->find($selector, $options);
366
      $events[$template_id] = [];
367
      /** @var \Drupal\mongodb_watchdog\Event $event */
368
      foreach ($cursor as $event) {
369
        $events[$event->requestTracking_sequence] = [
370
          $template,
371
          $event,
372
        ];
373
      }
374
    }
375
    return $events;
376
  }
377
378
  public function requestTemplates(string $unsafe_request_id) {
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
379
    $request_id = "${unsafe_request_id}";
380
    $selector = ['_id' => $request_id];
381
382
    $doc = $this->trackerCollection()->findOne($selector, static::LEGACY_TYPE_MAP);
383
    if (empty($doc) || empty($doc['templates'])) {
384
      return [];
385
    }
386
387
    $selector = ['_id' => ['$in' => $doc['templates']]];
388
    $options = [
389
      'typeMap' => [
390
        'array' => 'array',
391
        'document' => 'array',
392
        'root' => '\Drupal\mongodb_watchdog\EventTemplate',
393
      ],
394
    ];
395
    $templates = [];
396
    $cursor = $this->templateCollection()->find($selector, $options);
397
    /** @var \Drupal\mongodb_watchdog\EventTemplate $template */
398
    foreach ($cursor as $template) {
399
      $templates[$template->_id] = $template;
400
    }
401
    return $templates;
402
  }
403
404
  /**
405
   * Return the request events tracker collection.
406
   *
407
   * @return \MongoDB\Collection
408
   *   The collection.
409
   */
410
  public function trackerCollection() {
411
    return $this->database->selectCollection(static::TRACKER_COLLECTION);
412
  }
413
414
  /**
415
   * Return the event templates collection.
416
   *
417
   * @return \MongoDB\Collection
418
   *   The collection.
419
   */
420
  public function templateCollection() {
421
    return $this->database->selectCollection(static::TEMPLATE_COLLECTION);
422
  }
423
424
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
425