[!!!][FEATURE] Introduce PSR-3 Logging
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Log / LogLevel.php
1 <?php
2 namespace TYPO3\CMS\Core\Log;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Log\InvalidArgumentException;
18
19 /**
20 * Log levels according to RFC 3164
21 */
22 class LogLevel extends \Psr\Log\LogLevel
23 {
24 /**
25 * Reverse look up of log level to level name.
26 *
27 * @var array
28 */
29 protected static $levels = [
30 self::EMERGENCY,
31 self::ALERT,
32 self::CRITICAL,
33 self::ERROR,
34 self::WARNING,
35 self::NOTICE,
36 self::INFO,
37 self::DEBUG,
38 ];
39
40 /**
41 * Resolves the name of a log level and returns it in upper case letters
42 *
43 * @param int $level Log level.
44 * @return string Log level name.
45 */
46 public static function getName(int $level): string
47 {
48 return strtoupper(static::getInternalName($level));
49 }
50
51 /**
52 * Resolves the name of the log level and returns its internal string representation
53 *
54 * @param int $level
55 * @return string
56 */
57 public static function getInternalName(int $level): string
58 {
59 self::validateLevel($level);
60 return static::$levels[$level];
61 }
62
63 /**
64 * Checks a level for validity,
65 * whether it is an integer and in the range of 0-7.
66 *
67 * @param int $level log level to validate
68 * @return bool TRUE if the given log level is valid, FALSE otherwise
69 */
70 public static function isValidLevel(int $level): bool
71 {
72 return isset(static::$levels[$level]);
73 }
74
75 /**
76 * Validates a log level.
77 *
78 * @param int $level log level to validate
79 * @throws InvalidArgumentException if the given log level is invalid
80 */
81 public static function validateLevel(int $level): void
82 {
83 if (!self::isValidLevel($level)) {
84 throw new InvalidArgumentException('Invalid Log Level ' . $level, 1321637121);
85 }
86 }
87
88 /**
89 * Normalizes level by converting it from string to integer
90 *
91 * @param string|int $level
92 * @return int
93 */
94 public static function normalizeLevel($level): int
95 {
96 if (is_string($level)) {
97 if (!defined(__CLASS__ . '::' . strtoupper($level))) {
98 throw new InvalidArgumentException('Invalid Log Level ' . $level, 1550247164);
99 }
100 return array_search(strtolower($level), self::$levels, true);
101 }
102
103 return (int)$level;
104 }
105 }