InMemoryLogWriter.php 2 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\Adminpanel\Log;

20
use TYPO3\CMS\Adminpanel\Utility\MemoryUtility;
21
22
23
24
25
26
27
28
29
30
31
use TYPO3\CMS\Core\Log\LogLevel;
use TYPO3\CMS\Core\Log\LogRecord;
use TYPO3\CMS\Core\Log\Writer\AbstractWriter;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Log writer that writes the log records into a static public class variable
 * for InMemory processing
 */
class InMemoryLogWriter extends AbstractWriter
{
32
33
34
    /**
     * @var LogRecord[]
     */
35
36
    public static $log = [];

37
38
39
    /**
     * @var bool
     */
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    private static $memoryLock = false;

    /**
     * Writes the log record
     *
     * @param LogRecord $record Log record
     * @return self
     * @throws \RuntimeException
     */
    public function writeLog(LogRecord $record): self
    {
        // Guard: Locked Writer
        if (self::$memoryLock === true) {
            return $this;
        }

        // Guard: Memory Usage
57
        if (MemoryUtility::isMemoryConsumptionTooHigh()) {
58
59
60
61
62
63
64
65
66
67
            $this->lockWriter();
            return $this;
        }

        self::$log[] = $record;

        return $this;
    }

    /**
68
     * Lock writer and add an info message that there may potentially be more entries.
69
70
71
72
73
74
75
76
77
78
79
80
81
82
     */
    protected function lockWriter(): void
    {
        self::$memoryLock = true;
        /** @var LogRecord $record */
        $record = GeneralUtility::makeInstance(
            LogRecord::class,
            'TYPO3.CMS.AdminPanel.Log.InMemoryLogWriter',
            LogLevel::INFO,
            '... Further log entries omitted, memory usage too high.'
        );
        self::$log[] = $record;
    }
}