Logger.php 17 KB

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