Logger.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog;
  11. use DateTimeZone;
  12. use Monolog\Handler\HandlerInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Psr\Log\InvalidArgumentException;
  15. use Psr\Log\LogLevel;
  16. use Throwable;
  17. use Stringable;
  18. /**
  19. * Monolog log channel
  20. *
  21. * It contains a stack of Handlers and a stack of Processors,
  22. * and uses them to store records that are added to it.
  23. *
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. *
  26. * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY
  27. * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY'
  28. * @phpstan-type Record array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[]}
  29. */
  30. class Logger implements LoggerInterface, ResettableInterface
  31. {
  32. /**
  33. * Detailed debug information
  34. */
  35. public const DEBUG = 100;
  36. /**
  37. * Interesting events
  38. *
  39. * Examples: User logs in, SQL logs.
  40. */
  41. public const INFO = 200;
  42. /**
  43. * Uncommon events
  44. */
  45. public const NOTICE = 250;
  46. /**
  47. * Exceptional occurrences that are not errors
  48. *
  49. * Examples: Use of deprecated APIs, poor use of an API,
  50. * undesirable things that are not necessarily wrong.
  51. */
  52. public const WARNING = 300;
  53. /**
  54. * Runtime errors
  55. */
  56. public const ERROR = 400;
  57. /**
  58. * Critical conditions
  59. *
  60. * Example: Application component unavailable, unexpected exception.
  61. */
  62. public const CRITICAL = 500;
  63. /**
  64. * Action must be taken immediately
  65. *
  66. * Example: Entire website down, database unavailable, etc.
  67. * This should trigger the SMS alerts and wake you up.
  68. */
  69. public const ALERT = 550;
  70. /**
  71. * Urgent alert.
  72. */
  73. public const EMERGENCY = 600;
  74. /**
  75. * Monolog API version
  76. *
  77. * This is only bumped when API breaks are done and should
  78. * follow the major version of the library
  79. *
  80. * @var int
  81. */
  82. public const API = 2;
  83. /**
  84. * This is a static variable and not a constant to serve as an extension point for custom levels
  85. *
  86. * @var array<int, string> $levels Logging levels with the levels as key
  87. *
  88. * @phpstan-var array<Level, LevelName> $levels Logging levels with the levels as key
  89. */
  90. protected static $levels = [
  91. self::DEBUG => 'DEBUG',
  92. self::INFO => 'INFO',
  93. self::NOTICE => 'NOTICE',
  94. self::WARNING => 'WARNING',
  95. self::ERROR => 'ERROR',
  96. self::CRITICAL => 'CRITICAL',
  97. self::ALERT => 'ALERT',
  98. self::EMERGENCY => 'EMERGENCY',
  99. ];
  100. /**
  101. * @var string
  102. */
  103. protected $name;
  104. /**
  105. * The handler stack
  106. *
  107. * @var HandlerInterface[]
  108. */
  109. protected $handlers;
  110. /**
  111. * Processors that will process all log records
  112. *
  113. * To process records of a single handler instead, add the processor on that specific handler
  114. *
  115. * @var callable[]
  116. */
  117. protected $processors;
  118. /**
  119. * @var bool
  120. */
  121. protected $microsecondTimestamps = true;
  122. /**
  123. * @var DateTimeZone
  124. */
  125. protected $timezone;
  126. /**
  127. * @var callable|null
  128. */
  129. protected $exceptionHandler;
  130. /**
  131. * @psalm-param array<callable(array): array> $processors
  132. *
  133. * @param string $name The logging channel, a simple descriptive name that is attached to all log records
  134. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  135. * @param callable[] $processors Optional array of processors
  136. * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used
  137. */
  138. public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null)
  139. {
  140. $this->name = $name;
  141. $this->setHandlers($handlers);
  142. $this->processors = $processors;
  143. $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  144. }
  145. public function getName(): string
  146. {
  147. return $this->name;
  148. }
  149. /**
  150. * Return a new cloned instance with the name changed
  151. */
  152. public function withName(string $name): self
  153. {
  154. $new = clone $this;
  155. $new->name = $name;
  156. return $new;
  157. }
  158. /**
  159. * Pushes a handler on to the stack.
  160. */
  161. public function pushHandler(HandlerInterface $handler): self
  162. {
  163. array_unshift($this->handlers, $handler);
  164. return $this;
  165. }
  166. /**
  167. * Pops a handler from the stack
  168. *
  169. * @throws \LogicException If empty handler stack
  170. */
  171. public function popHandler(): HandlerInterface
  172. {
  173. if (!$this->handlers) {
  174. throw new \LogicException('You tried to pop from an empty handler stack.');
  175. }
  176. return array_shift($this->handlers);
  177. }
  178. /**
  179. * Set handlers, replacing all existing ones.
  180. *
  181. * If a map is passed, keys will be ignored.
  182. *
  183. * @param HandlerInterface[] $handlers
  184. */
  185. public function setHandlers(array $handlers): self
  186. {
  187. $this->handlers = [];
  188. foreach (array_reverse($handlers) as $handler) {
  189. $this->pushHandler($handler);
  190. }
  191. return $this;
  192. }
  193. /**
  194. * @return HandlerInterface[]
  195. */
  196. public function getHandlers(): array
  197. {
  198. return $this->handlers;
  199. }
  200. /**
  201. * Adds a processor on to the stack.
  202. */
  203. public function pushProcessor(callable $callback): self
  204. {
  205. array_unshift($this->processors, $callback);
  206. return $this;
  207. }
  208. /**
  209. * Removes the processor on top of the stack and returns it.
  210. *
  211. * @throws \LogicException If empty processor stack
  212. * @return callable
  213. */
  214. public function popProcessor(): callable
  215. {
  216. if (!$this->processors) {
  217. throw new \LogicException('You tried to pop from an empty processor stack.');
  218. }
  219. return array_shift($this->processors);
  220. }
  221. /**
  222. * @return callable[]
  223. */
  224. public function getProcessors(): array
  225. {
  226. return $this->processors;
  227. }
  228. /**
  229. * Control the use of microsecond resolution timestamps in the 'datetime'
  230. * member of new records.
  231. *
  232. * As of PHP7.1 microseconds are always included by the engine, so
  233. * there is no performance penalty and Monolog 2 enabled microseconds
  234. * by default. This function lets you disable them though in case you want
  235. * to suppress microseconds from the output.
  236. *
  237. * @param bool $micro True to use microtime() to create timestamps
  238. */
  239. public function useMicrosecondTimestamps(bool $micro): void
  240. {
  241. $this->microsecondTimestamps = $micro;
  242. }
  243. /**
  244. * Adds a log record.
  245. *
  246. * @param int $level The logging level
  247. * @param string $message The log message
  248. * @param mixed[] $context The log context
  249. * @return bool Whether the record has been processed
  250. *
  251. * @phpstan-param Level $level
  252. */
  253. public function addRecord(int $level, string $message, array $context = []): bool
  254. {
  255. $offset = 0;
  256. $record = null;
  257. foreach ($this->handlers as $handler) {
  258. if (null === $record) {
  259. // skip creating the record as long as no handler is going to handle it
  260. if (!$handler->isHandling(['level' => $level])) {
  261. continue;
  262. }
  263. $levelName = static::getLevelName($level);
  264. $record = [
  265. 'message' => $message,
  266. 'context' => $context,
  267. 'level' => $level,
  268. 'level_name' => $levelName,
  269. 'channel' => $this->name,
  270. 'datetime' => new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  271. 'extra' => [],
  272. ];
  273. try {
  274. foreach ($this->processors as $processor) {
  275. $record = $processor($record);
  276. }
  277. } catch (Throwable $e) {
  278. $this->handleException($e, $record);
  279. return true;
  280. }
  281. }
  282. // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted
  283. try {
  284. if (true === $handler->handle($record)) {
  285. break;
  286. }
  287. } catch (Throwable $e) {
  288. $this->handleException($e, $record);
  289. return true;
  290. }
  291. }
  292. return null !== $record;
  293. }
  294. /**
  295. * Ends a log cycle and frees all resources used by handlers.
  296. *
  297. * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  298. * Handlers that have been closed should be able to accept log records again and re-open
  299. * themselves on demand, but this may not always be possible depending on implementation.
  300. *
  301. * This is useful at the end of a request and will be called automatically on every handler
  302. * when they get destructed.
  303. */
  304. public function close(): void
  305. {
  306. foreach ($this->handlers as $handler) {
  307. $handler->close();
  308. }
  309. }
  310. /**
  311. * Ends a log cycle and resets all handlers and processors to their initial state.
  312. *
  313. * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  314. * state, and getting it back to a state in which it can receive log records again.
  315. *
  316. * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  317. * have a long running process like a worker or an application server serving multiple requests
  318. * in one process.
  319. */
  320. public function reset(): void
  321. {
  322. foreach ($this->handlers as $handler) {
  323. if ($handler instanceof ResettableInterface) {
  324. $handler->reset();
  325. }
  326. }
  327. foreach ($this->processors as $processor) {
  328. if ($processor instanceof ResettableInterface) {
  329. $processor->reset();
  330. }
  331. }
  332. }
  333. /**
  334. * Gets all supported logging levels.
  335. *
  336. * @return array<string, int> Assoc array with human-readable level names => level codes.
  337. * @phpstan-return array<LevelName, Level>
  338. */
  339. public static function getLevels(): array
  340. {
  341. return array_flip(static::$levels);
  342. }
  343. /**
  344. * Gets the name of the logging level.
  345. *
  346. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  347. *
  348. * @phpstan-param Level $level
  349. * @phpstan-return LevelName
  350. */
  351. public static function getLevelName(int $level): string
  352. {
  353. if (!isset(static::$levels[$level])) {
  354. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  355. }
  356. return static::$levels[$level];
  357. }
  358. /**
  359. * Converts PSR-3 levels to Monolog ones if necessary
  360. *
  361. * @param string|int $level Level number (monolog) or name (PSR-3)
  362. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  363. *
  364. * @phpstan-param Level|LevelName|LogLevel::* $level
  365. * @phpstan-return Level
  366. */
  367. public static function toMonologLevel($level): int
  368. {
  369. if (is_string($level)) {
  370. if (is_numeric($level)) {
  371. /** @phpstan-ignore-next-line */
  372. return intval($level);
  373. }
  374. // Contains chars of all log levels and avoids using strtoupper() which may have
  375. // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
  376. $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY');
  377. if (defined(__CLASS__.'::'.$upper)) {
  378. return constant(__CLASS__ . '::' . $upper);
  379. }
  380. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  381. }
  382. if (!is_int($level)) {
  383. throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  384. }
  385. return $level;
  386. }
  387. /**
  388. * Checks whether the Logger has a handler that listens on the given level
  389. *
  390. * @phpstan-param Level $level
  391. */
  392. public function isHandling(int $level): bool
  393. {
  394. $record = [
  395. 'level' => $level,
  396. ];
  397. foreach ($this->handlers as $handler) {
  398. if ($handler->isHandling($record)) {
  399. return true;
  400. }
  401. }
  402. return false;
  403. }
  404. /**
  405. * Set a custom exception handler that will be called if adding a new record fails
  406. *
  407. * The callable will receive an exception object and the record that failed to be logged
  408. */
  409. public function setExceptionHandler(?callable $callback): self
  410. {
  411. $this->exceptionHandler = $callback;
  412. return $this;
  413. }
  414. public function getExceptionHandler(): ?callable
  415. {
  416. return $this->exceptionHandler;
  417. }
  418. /**
  419. * Adds a log record at an arbitrary level.
  420. *
  421. * This method allows for compatibility with common interfaces.
  422. *
  423. * @param mixed $level The log level
  424. * @param string|Stringable $message The log message
  425. * @param mixed[] $context The log context
  426. *
  427. * @phpstan-param Level|LevelName|LogLevel::* $level
  428. */
  429. public function log($level, $message, array $context = []): void
  430. {
  431. if (!is_int($level) && !is_string($level)) {
  432. throw new \InvalidArgumentException('$level is expected to be a string or int');
  433. }
  434. $level = static::toMonologLevel($level);
  435. $this->addRecord($level, (string) $message, $context);
  436. }
  437. /**
  438. * Adds a log record at the DEBUG level.
  439. *
  440. * This method allows for compatibility with common interfaces.
  441. *
  442. * @param string|Stringable $message The log message
  443. * @param mixed[] $context The log context
  444. */
  445. public function debug($message, array $context = []): void
  446. {
  447. $this->addRecord(static::DEBUG, (string) $message, $context);
  448. }
  449. /**
  450. * Adds a log record at the INFO level.
  451. *
  452. * This method allows for compatibility with common interfaces.
  453. *
  454. * @param string|Stringable $message The log message
  455. * @param mixed[] $context The log context
  456. */
  457. public function info($message, array $context = []): void
  458. {
  459. $this->addRecord(static::INFO, (string) $message, $context);
  460. }
  461. /**
  462. * Adds a log record at the NOTICE level.
  463. *
  464. * This method allows for compatibility with common interfaces.
  465. *
  466. * @param string|Stringable $message The log message
  467. * @param mixed[] $context The log context
  468. */
  469. public function notice($message, array $context = []): void
  470. {
  471. $this->addRecord(static::NOTICE, (string) $message, $context);
  472. }
  473. /**
  474. * Adds a log record at the WARNING level.
  475. *
  476. * This method allows for compatibility with common interfaces.
  477. *
  478. * @param string|Stringable $message The log message
  479. * @param mixed[] $context The log context
  480. */
  481. public function warning($message, array $context = []): void
  482. {
  483. $this->addRecord(static::WARNING, (string) $message, $context);
  484. }
  485. /**
  486. * Adds a log record at the ERROR level.
  487. *
  488. * This method allows for compatibility with common interfaces.
  489. *
  490. * @param string|Stringable $message The log message
  491. * @param mixed[] $context The log context
  492. */
  493. public function error($message, array $context = []): void
  494. {
  495. $this->addRecord(static::ERROR, (string) $message, $context);
  496. }
  497. /**
  498. * Adds a log record at the CRITICAL level.
  499. *
  500. * This method allows for compatibility with common interfaces.
  501. *
  502. * @param string|Stringable $message The log message
  503. * @param mixed[] $context The log context
  504. */
  505. public function critical($message, array $context = []): void
  506. {
  507. $this->addRecord(static::CRITICAL, (string) $message, $context);
  508. }
  509. /**
  510. * Adds a log record at the ALERT level.
  511. *
  512. * This method allows for compatibility with common interfaces.
  513. *
  514. * @param string|Stringable $message The log message
  515. * @param mixed[] $context The log context
  516. */
  517. public function alert($message, array $context = []): void
  518. {
  519. $this->addRecord(static::ALERT, (string) $message, $context);
  520. }
  521. /**
  522. * Adds a log record at the EMERGENCY level.
  523. *
  524. * This method allows for compatibility with common interfaces.
  525. *
  526. * @param string|Stringable $message The log message
  527. * @param mixed[] $context The log context
  528. */
  529. public function emergency($message, array $context = []): void
  530. {
  531. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  532. }
  533. /**
  534. * Sets the timezone to be used for the timestamp of log records.
  535. */
  536. public function setTimezone(DateTimeZone $tz): self
  537. {
  538. $this->timezone = $tz;
  539. return $this;
  540. }
  541. /**
  542. * Returns the timezone to be used for the timestamp of log records.
  543. */
  544. public function getTimezone(): DateTimeZone
  545. {
  546. return $this->timezone;
  547. }
  548. /**
  549. * Delegates exception management to the custom exception handler,
  550. * or throws the exception if no custom handler is set.
  551. *
  552. * @param array $record
  553. * @phpstan-param Record $record
  554. */
  555. protected function handleException(Throwable $e, array $record): void
  556. {
  557. if (!$this->exceptionHandler) {
  558. throw $e;
  559. }
  560. ($this->exceptionHandler)($e, $record);
  561. }
  562. }