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 Monolog\Processor\ProcessorInterface;
  14. use Psr\Log\LoggerInterface;
  15. use Psr\Log\InvalidArgumentException;
  16. use Psr\Log\LogLevel;
  17. use Throwable;
  18. use Stringable;
  19. /**
  20. * Monolog log channel
  21. *
  22. * It contains a stack of Handlers and a stack of Processors,
  23. * and uses them to store records that are added to it.
  24. *
  25. * @author Jordi Boggiano <j.boggiano@seld.be>
  26. *
  27. * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY
  28. * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY'
  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 array<(callable(LogRecord): LogRecord)|ProcessorInterface>
  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. * @param string $name The logging channel, a simple descriptive name that is attached to all log records
  132. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  133. * @param callable[] $processors Optional array of processors
  134. * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used
  135. *
  136. * @phpstan-param array<(callable(LogRecord): LogRecord)|ProcessorInterface> $processors
  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): self
  240. {
  241. $this->microsecondTimestamps = $micro;
  242. return $this;
  243. }
  244. /**
  245. * Adds a log record.
  246. *
  247. * @param int $level The logging level
  248. * @param string $message The log message
  249. * @param mixed[] $context The log context
  250. * @return bool Whether the record has been processed
  251. *
  252. * @phpstan-param Level $level
  253. */
  254. public function addRecord(int $level, string $message, array $context = []): bool
  255. {
  256. $recordInitialized = count($this->processors) === 0;
  257. $record = new LogRecord(
  258. message: $message,
  259. context: $context,
  260. level: $level,
  261. channel: $this->name,
  262. datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  263. extra: [],
  264. );
  265. $handled = false;
  266. foreach ($this->handlers as $handler) {
  267. if (false === $recordInitialized) {
  268. // skip initializing the record as long as no handler is going to handle it
  269. if (!$handler->isHandling($record)) {
  270. continue;
  271. }
  272. try {
  273. foreach ($this->processors as $processor) {
  274. $record = $processor($record);
  275. }
  276. $recordInitialized = true;
  277. } catch (Throwable $e) {
  278. $this->handleException($e, $record);
  279. return true;
  280. }
  281. }
  282. // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted
  283. try {
  284. $handled = true;
  285. if (true === $handler->handle($record)) {
  286. break;
  287. }
  288. } catch (Throwable $e) {
  289. $this->handleException($e, $record);
  290. return true;
  291. }
  292. }
  293. return $handled;
  294. }
  295. /**
  296. * Ends a log cycle and frees all resources used by handlers.
  297. *
  298. * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  299. * Handlers that have been closed should be able to accept log records again and re-open
  300. * themselves on demand, but this may not always be possible depending on implementation.
  301. *
  302. * This is useful at the end of a request and will be called automatically on every handler
  303. * when they get destructed.
  304. */
  305. public function close(): void
  306. {
  307. foreach ($this->handlers as $handler) {
  308. $handler->close();
  309. }
  310. }
  311. /**
  312. * Ends a log cycle and resets all handlers and processors to their initial state.
  313. *
  314. * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  315. * state, and getting it back to a state in which it can receive log records again.
  316. *
  317. * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  318. * have a long running process like a worker or an application server serving multiple requests
  319. * in one process.
  320. */
  321. public function reset(): void
  322. {
  323. foreach ($this->handlers as $handler) {
  324. if ($handler instanceof ResettableInterface) {
  325. $handler->reset();
  326. }
  327. }
  328. foreach ($this->processors as $processor) {
  329. if ($processor instanceof ResettableInterface) {
  330. $processor->reset();
  331. }
  332. }
  333. }
  334. /**
  335. * Gets all supported logging levels.
  336. *
  337. * @return array<string, int> Assoc array with human-readable level names => level codes.
  338. * @phpstan-return array<LevelName, Level>
  339. */
  340. public static function getLevels(): array
  341. {
  342. return array_flip(static::$levels);
  343. }
  344. /**
  345. * Gets the name of the logging level.
  346. *
  347. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  348. *
  349. * @phpstan-param Level $level
  350. * @phpstan-return LevelName
  351. */
  352. public static function getLevelName(int $level): string
  353. {
  354. if (!isset(static::$levels[$level])) {
  355. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  356. }
  357. return static::$levels[$level];
  358. }
  359. /**
  360. * Converts PSR-3 levels to Monolog ones if necessary
  361. *
  362. * @param string|int $level Level number (monolog) or name (PSR-3)
  363. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  364. *
  365. * @phpstan-param Level|LevelName|LogLevel::* $level
  366. * @phpstan-return Level
  367. */
  368. public static function toMonologLevel($level): int
  369. {
  370. if (is_string($level)) {
  371. if (is_numeric($level)) {
  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 = new LogRecord(
  395. datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  396. channel: $this->name,
  397. message: '',
  398. level: $level,
  399. );
  400. foreach ($this->handlers as $handler) {
  401. if ($handler->isHandling($record)) {
  402. return true;
  403. }
  404. }
  405. return false;
  406. }
  407. /**
  408. * Set a custom exception handler that will be called if adding a new record fails
  409. *
  410. * The callable will receive an exception object and the record that failed to be logged
  411. */
  412. public function setExceptionHandler(?callable $callback): self
  413. {
  414. $this->exceptionHandler = $callback;
  415. return $this;
  416. }
  417. public function getExceptionHandler(): ?callable
  418. {
  419. return $this->exceptionHandler;
  420. }
  421. /**
  422. * Adds a log record at an arbitrary level.
  423. *
  424. * This method allows for compatibility with common interfaces.
  425. *
  426. * @param mixed $level The log level
  427. * @param string|Stringable $message The log message
  428. * @param mixed[] $context The log context
  429. *
  430. * @phpstan-param Level|LevelName|LogLevel::* $level
  431. */
  432. public function log($level, string|\Stringable $message, array $context = []): void
  433. {
  434. if (!is_int($level) && !is_string($level)) {
  435. throw new \InvalidArgumentException('$level is expected to be a string or int');
  436. }
  437. $level = static::toMonologLevel($level);
  438. $this->addRecord($level, (string) $message, $context);
  439. }
  440. /**
  441. * Adds a log record at the DEBUG level.
  442. *
  443. * This method allows for compatibility with common interfaces.
  444. *
  445. * @param string|Stringable $message The log message
  446. * @param mixed[] $context The log context
  447. */
  448. public function debug(string|\Stringable $message, array $context = []): void
  449. {
  450. $this->addRecord(static::DEBUG, (string) $message, $context);
  451. }
  452. /**
  453. * Adds a log record at the INFO level.
  454. *
  455. * This method allows for compatibility with common interfaces.
  456. *
  457. * @param string|Stringable $message The log message
  458. * @param mixed[] $context The log context
  459. */
  460. public function info(string|\Stringable $message, array $context = []): void
  461. {
  462. $this->addRecord(static::INFO, (string) $message, $context);
  463. }
  464. /**
  465. * Adds a log record at the NOTICE level.
  466. *
  467. * This method allows for compatibility with common interfaces.
  468. *
  469. * @param string|Stringable $message The log message
  470. * @param mixed[] $context The log context
  471. */
  472. public function notice(string|\Stringable $message, array $context = []): void
  473. {
  474. $this->addRecord(static::NOTICE, (string) $message, $context);
  475. }
  476. /**
  477. * Adds a log record at the WARNING level.
  478. *
  479. * This method allows for compatibility with common interfaces.
  480. *
  481. * @param string|Stringable $message The log message
  482. * @param mixed[] $context The log context
  483. */
  484. public function warning(string|\Stringable $message, array $context = []): void
  485. {
  486. $this->addRecord(static::WARNING, (string) $message, $context);
  487. }
  488. /**
  489. * Adds a log record at the ERROR level.
  490. *
  491. * This method allows for compatibility with common interfaces.
  492. *
  493. * @param string|Stringable $message The log message
  494. * @param mixed[] $context The log context
  495. */
  496. public function error(string|\Stringable $message, array $context = []): void
  497. {
  498. $this->addRecord(static::ERROR, (string) $message, $context);
  499. }
  500. /**
  501. * Adds a log record at the CRITICAL level.
  502. *
  503. * This method allows for compatibility with common interfaces.
  504. *
  505. * @param string|Stringable $message The log message
  506. * @param mixed[] $context The log context
  507. */
  508. public function critical(string|\Stringable $message, array $context = []): void
  509. {
  510. $this->addRecord(static::CRITICAL, (string) $message, $context);
  511. }
  512. /**
  513. * Adds a log record at the ALERT level.
  514. *
  515. * This method allows for compatibility with common interfaces.
  516. *
  517. * @param string|Stringable $message The log message
  518. * @param mixed[] $context The log context
  519. */
  520. public function alert(string|\Stringable $message, array $context = []): void
  521. {
  522. $this->addRecord(static::ALERT, (string) $message, $context);
  523. }
  524. /**
  525. * Adds a log record at the EMERGENCY level.
  526. *
  527. * This method allows for compatibility with common interfaces.
  528. *
  529. * @param string|Stringable $message The log message
  530. * @param mixed[] $context The log context
  531. */
  532. public function emergency(string|\Stringable $message, array $context = []): void
  533. {
  534. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  535. }
  536. /**
  537. * Sets the timezone to be used for the timestamp of log records.
  538. */
  539. public function setTimezone(DateTimeZone $tz): self
  540. {
  541. $this->timezone = $tz;
  542. return $this;
  543. }
  544. /**
  545. * Returns the timezone to be used for the timestamp of log records.
  546. */
  547. public function getTimezone(): DateTimeZone
  548. {
  549. return $this->timezone;
  550. }
  551. /**
  552. * Delegates exception management to the custom exception handler,
  553. * or throws the exception if no custom handler is set.
  554. */
  555. protected function handleException(Throwable $e, LogRecord $record): void
  556. {
  557. if (!$this->exceptionHandler) {
  558. throw $e;
  559. }
  560. ($this->exceptionHandler)($e, $record);
  561. }
  562. }