Skip to content

Commit

Permalink
Update Monolog to version 3 (see #7142)
Browse files Browse the repository at this point in the history
Description
-----------

Fixes #6706

First try to update monolog to verson 3. Please check the unit tests.

Commits
-------

e99f2ba5 Update to monolog 3
24a0746f Migrate to monolog v3
8e5b7ad9 Fix unit test
b7ad6013 Remove debug statement
8945b9c4 Fix ecs
b15b9e36 Fix level comparison and phpstan error
f17f3b20 Fix php stan import because we use the record class instead of an array
3ecea17e Fix ecs
95b96708 Fix the unit tests

Co-authored-by: leofeyer <[email protected]>
  • Loading branch information
Wusch and leofeyer authored Jun 24, 2024
1 parent 0dfcc53 commit b3785a0
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 244 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"league/flysystem": "^3.7",
"league/flysystem-bundle": "^3.0",
"matthiasmullie/minify": "^1.3",
"monolog/monolog": "^2.0",
"monolog/monolog": "^3.0",
"nelmio/cors-bundle": "^2.0.1",
"nelmio/security-bundle": "^3.0",
"nikic/php-parser": "^4.9",
Expand Down
3 changes: 2 additions & 1 deletion src/Command/CrawlCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Contao\CoreBundle\Crawl\Monolog\CrawlCsvLogHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\GroupHandler;
use Monolog\Level;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
Expand Down Expand Up @@ -180,7 +181,7 @@ private function createLogger(OutputInterface $output, InputInterface $input): L
$this->filesystem->remove($input->getOption('debug-csv-path'));
}

$csvDebugHandler = new CrawlCsvLogHandler($input->getOption('debug-csv-path'), Logger::DEBUG);
$csvDebugHandler = new CrawlCsvLogHandler($input->getOption('debug-csv-path'), Level::Debug);
$handlers[] = $csvDebugHandler;
}

Expand Down
17 changes: 9 additions & 8 deletions src/Crawl/Monolog/CrawlCsvLogHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace Contao\CoreBundle\Crawl\Monolog;

use Monolog\Handler\StreamHandler;
use Monolog\LogRecord;
use Terminal42\Escargot\CrawlUri;

class CrawlCsvLogHandler extends StreamHandler
Expand All @@ -33,20 +34,20 @@ public function setFilterSource(string $filterSource): self
return $this;
}

protected function streamWrite($stream, array $record): void
protected function streamWrite($stream, LogRecord $record): void
{
if (!isset($record['context']['source'])) {
if (!isset($record->context['source'])) {
return;
}

if ($this->filterSource && $this->filterSource !== $record['context']['source']) {
if ($this->filterSource && $this->filterSource !== $record->context['source']) {
return;
}

$crawlUri = null;

if (($record['context']['crawlUri'] ?? null) instanceof CrawlUri) {
$crawlUri = $record['context']['crawlUri'];
if (($record->context['crawlUri'] ?? null) instanceof CrawlUri) {
$crawlUri = $record->context['crawlUri'];
}

$stat = fstat($stream);
Expand All @@ -57,13 +58,13 @@ protected function streamWrite($stream, array $record): void
}

$columns = [
$record['datetime']->format(self::DATETIME_FORMAT),
$record['context']['source'],
$record->datetime->format(self::DATETIME_FORMAT),
$record->context['source'],
!$crawlUri ? '---' : (string) $crawlUri->getUri(),
!$crawlUri ? '---' : (string) $crawlUri->getFoundOn(),
!$crawlUri ? '---' : $crawlUri->getLevel(),
!$crawlUri ? '---' : implode(', ', $crawlUri->getTags()),
preg_replace('/\r\n|\n|\r/', ' ', $record['message']),
preg_replace('/\r\n|\n|\r/', ' ', $record->message),
];

fputcsv($stream, $columns);
Expand Down
22 changes: 10 additions & 12 deletions src/Monolog/ContaoTableHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use Monolog\Level;
use Monolog\LogRecord;

class ContaoTableHandler extends AbstractProcessingHandler
{
Expand All @@ -26,22 +27,22 @@ class ContaoTableHandler extends AbstractProcessingHandler
*/
public function __construct(
private readonly \Closure $connection,
$level = Logger::DEBUG,
$level = Level::Debug,
bool $bubble = true,
) {
parent::__construct($level, $bubble);
}

public function handle(array $record): bool
public function handle(LogRecord $record): bool
{
if (!$this->isHandling($record)) {
return false;
}

$record = $this->processRecord($record);
$record['formatted'] = $this->getFormatter()->format($record);
$record->formatted = $this->getFormatter()->format($record);

if (!isset($record['extra']['contao']) || !$record['extra']['contao'] instanceof ContaoContext) {
if (!isset($record->extra['contao']) || !$record->extra['contao'] instanceof ContaoContext) {
return false;
}

Expand All @@ -54,17 +55,14 @@ public function handle(array $record): bool
return !$this->bubble;
}

protected function write(array $record): void
protected function write(LogRecord $record): void
{
/** @var \DateTime $date */
$date = $record['datetime'];

/** @var ContaoContext $context */
$context = $record['extra']['contao'];
$context = $record->extra['contao'];

($this->connection)()->insert('tl_log', [
'tstamp' => $date->format('U'),
'text' => StringUtil::specialchars((string) $record['formatted']),
'tstamp' => $record->datetime->format('U'),
'text' => StringUtil::specialchars((string) $record->formatted),
'source' => (string) $context->getSource(),
'action' => (string) $context->getAction(),
'username' => (string) $context->getUsername(),
Expand Down
18 changes: 9 additions & 9 deletions src/Monolog/ContaoTableProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

use Contao\CoreBundle\Routing\ScopeMatcher;
use Contao\PageModel;
use Monolog\Logger;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
Expand All @@ -35,15 +36,15 @@ public function __construct(
/**
* Move the Contao context into the "extra" section.
*/
public function __invoke(array $record): array
public function __invoke(LogRecord $record): LogRecord
{
if (!isset($record['context']['contao']) || !$record['context']['contao'] instanceof ContaoContext) {
if (!isset($record->context['contao']) || !$record->context['contao'] instanceof ContaoContext) {
return $record;
}

$context = $record['context']['contao'];
$context = $record->context['contao'];
$request = $this->requestStack->getCurrentRequest();
$level = $record['level'];
$level = $record->level;

$this->updateAction($context, $level);
$this->updateBrowser($context, $request);
Expand All @@ -52,19 +53,18 @@ public function __invoke(array $record): array
$this->updateUri($context, $request);
$this->updatePageId($context, $request);

$record['extra']['contao'] = $context;
unset($record['context']['contao']);
$record->extra['contao'] = $context;

return $record;
}

private function updateAction(ContaoContext $context, int $level): void
private function updateAction(ContaoContext $context, Level $level): void
{
if (null !== $context->getAction()) {
return;
}

if ($level >= Logger::ERROR) {
if ($level->isHigherThan(Level::Warning)) {
$context->setAction(ContaoContext::ERROR);
} else {
$context->setAction(ContaoContext::GENERAL);
Expand Down
26 changes: 15 additions & 11 deletions tests/Crawl/Monolog/CrawlCsvLogHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
namespace Contao\CoreBundle\Tests\Crawl\Monolog;

use Contao\CoreBundle\Crawl\Monolog\CrawlCsvLogHandler;
use Monolog\Logger;
use Monolog\Level;
use Monolog\LogRecord;
use Nyholm\Psr7\Uri;
use PHPUnit\Framework\TestCase;
use Terminal42\Escargot\CrawlUri;
Expand All @@ -31,8 +32,10 @@ public function testWritesCsvStream(\DateTimeImmutable $dt, array $context, stri
fwrite($stream, $existingCsvContent);
}

$record = $this->getRecord($dt, $message, $context);

$handler = new CrawlCsvLogHandler($stream);
$handler->handle(['level' => Logger::DEBUG, 'level_name' => 'DEBUG', 'channel' => 'test', 'message' => $message, 'extra' => [], 'context' => $context, 'datetime' => $dt]);
$handler->handle($record);

rewind($stream);
$content = stream_get_contents($stream);
Expand All @@ -45,18 +48,14 @@ public function testSourceFilter(): void
$dt = new \DateTimeImmutable();
$formattedDt = '"'.$dt->format(CrawlCsvLogHandler::DATETIME_FORMAT).'"';

$record = [
'level' => Logger::DEBUG,
'level_name' => 'DEBUG',
'message' => 'foobar',
'channel' => 'test',
'extra' => [],
'datetime' => $dt,
'context' => [
$record = $this->getRecord(
$dt,
'foobar',
[
'source' => 'source',
'crawlUri' => new CrawlUri(new Uri('https://contao.org'), 0),
],
];
);

$stream = fopen('php://memory', 'r+');
$handler = new CrawlCsvLogHandler($stream);
Expand Down Expand Up @@ -122,4 +121,9 @@ public static function writesCsvStreamProvider(): iterable
"foobar\rwith\nnew\r\nlines",
];
}

private function getRecord(\DateTimeImmutable $dt, string $message, array $context): LogRecord
{
return new LogRecord($dt, 'test', Level::Debug, $message, $context, []);
}
}
42 changes: 14 additions & 28 deletions tests/Monolog/ContaoTableHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,14 @@
use Contao\CoreBundle\Monolog\ContaoTableHandler;
use Contao\CoreBundle\Tests\TestCase;
use Doctrine\DBAL\Connection;
use Monolog\Level;
use Monolog\Logger;
use Monolog\LogRecord;

class ContaoTableHandlerTest extends TestCase
{
public function testHandlesContaoRecords(): void
{
$record = [
'level' => Logger::DEBUG,
'level_name' => 'DEBUG',
'channel' => 'test',
'extra' => ['contao' => new ContaoContext('foobar')],
'context' => [],
'datetime' => new \DateTimeImmutable(),
'message' => 'foobar',
];

$connection = $this->createMock(Connection::class);
$connection
->expects($this->once())
Expand All @@ -40,21 +32,14 @@ public function testHandlesContaoRecords(): void
;

$handler = new ContaoTableHandler(static fn () => $connection);
$record = $this->getRecord(['contao' => new ContaoContext('foobar')]);

$this->assertFalse($handler->handle($record));
}

public function testDoesNotHandleARecordIfTheLogLevelDoesNotMatch(): void
{
$record = [
'level' => Logger::DEBUG,
'level_name' => 'DEBUG',
'channel' => 'test',
'extra' => [],
'context' => [],
'datetime' => new \DateTimeImmutable(),
'message' => 'foobar',
];
$record = $this->getRecord([]);

$connection = $this->createMock(Connection::class);
$connection
Expand All @@ -70,15 +55,7 @@ public function testDoesNotHandleARecordIfTheLogLevelDoesNotMatch(): void

public function testDoesNotHandleARecordWithoutContaoContext(): void
{
$record = [
'level' => Logger::DEBUG,
'level_name' => 'DEBUG',
'channel' => 'test',
'extra' => ['contao' => null],
'context' => [],
'datetime' => new \DateTimeImmutable(),
'message' => 'foobar',
];
$record = $this->getRecord(['contao' => null]);

$connection = $this->createMock(Connection::class);
$connection
Expand All @@ -90,4 +67,13 @@ public function testDoesNotHandleARecordWithoutContaoContext(): void

$this->assertFalse($handler->handle($record));
}

/**
* The Contao context was moved to the "extra" section by the processor, so pass
* it as sixth argument to the LogRecord class.
*/
private function getRecord(array $context): LogRecord
{
return new LogRecord(new \DateTimeImmutable(), 'test', Level::Debug, 'foobar', [], $context);
}
}
Loading

0 comments on commit b3785a0

Please sign in to comment.