Logger.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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 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. * @param string $name The logging channel, a simple descriptive name that is attached to all log records
  124. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  125. * @param callable[] $processors Optional array of processors
  126. * @param ?DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used
  127. */
  128. public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null)
  129. {
  130. $this->name = $name;
  131. $this->setHandlers($handlers);
  132. $this->processors = $processors;
  133. $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  134. }
  135. public function getName(): string
  136. {
  137. return $this->name;
  138. }
  139. /**
  140. * Return a new cloned instance with the name changed
  141. */
  142. public function withName(string $name): self
  143. {
  144. $new = clone $this;
  145. $new->name = $name;
  146. return $new;
  147. }
  148. /**
  149. * Pushes a handler on to the stack.
  150. */
  151. public function pushHandler(HandlerInterface $handler): self
  152. {
  153. array_unshift($this->handlers, $handler);
  154. return $this;
  155. }
  156. /**
  157. * Pops a handler from the stack
  158. *
  159. * @throws \LogicException If empty handler stack
  160. */
  161. public function popHandler(): HandlerInterface
  162. {
  163. if (!$this->handlers) {
  164. throw new \LogicException('You tried to pop from an empty handler stack.');
  165. }
  166. return array_shift($this->handlers);
  167. }
  168. /**
  169. * Set handlers, replacing all existing ones.
  170. *
  171. * If a map is passed, keys will be ignored.
  172. *
  173. * @param HandlerInterface[] $handlers
  174. */
  175. public function setHandlers(array $handlers): self
  176. {
  177. $this->handlers = [];
  178. foreach (array_reverse($handlers) as $handler) {
  179. $this->pushHandler($handler);
  180. }
  181. return $this;
  182. }
  183. /**
  184. * @return HandlerInterface[]
  185. */
  186. public function getHandlers(): array
  187. {
  188. return $this->handlers;
  189. }
  190. /**
  191. * Adds a processor on to the stack.
  192. */
  193. public function pushProcessor(callable $callback): self
  194. {
  195. array_unshift($this->processors, $callback);
  196. return $this;
  197. }
  198. /**
  199. * Removes the processor on top of the stack and returns it.
  200. *
  201. * @throws \LogicException If empty processor stack
  202. * @return callable
  203. */
  204. public function popProcessor(): callable
  205. {
  206. if (!$this->processors) {
  207. throw new \LogicException('You tried to pop from an empty processor stack.');
  208. }
  209. return array_shift($this->processors);
  210. }
  211. /**
  212. * @return callable[]
  213. */
  214. public function getProcessors(): array
  215. {
  216. return $this->processors;
  217. }
  218. /**
  219. * Control the use of microsecond resolution timestamps in the 'datetime'
  220. * member of new records.
  221. *
  222. * On PHP7.0, generating microsecond resolution timestamps by calling
  223. * microtime(true), formatting the result via sprintf() and then parsing
  224. * the resulting string via \DateTime::createFromFormat() can incur
  225. * a measurable runtime overhead vs simple usage of DateTime to capture
  226. * a second resolution timestamp in systems which generate a large number
  227. * of log events.
  228. *
  229. * On PHP7.1 however microseconds are always included by the engine, so
  230. * this setting can be left alone unless you really want to suppress
  231. * microseconds in the output.
  232. *
  233. * @param bool $micro True to use microtime() to create timestamps
  234. */
  235. public function useMicrosecondTimestamps(bool $micro)
  236. {
  237. $this->microsecondTimestamps = $micro;
  238. }
  239. /**
  240. * Adds a log record.
  241. *
  242. * @param int $level The logging level
  243. * @param string $message The log message
  244. * @param array $context The log context
  245. * @return bool Whether the record has been processed
  246. */
  247. public function addRecord(int $level, string $message, array $context = []): bool
  248. {
  249. // check if any handler will handle this message so we can return early and save cycles
  250. $handlerKey = null;
  251. foreach ($this->handlers as $key => $handler) {
  252. if ($handler->isHandling(['level' => $level])) {
  253. $handlerKey = $key;
  254. break;
  255. }
  256. }
  257. if (null === $handlerKey) {
  258. return false;
  259. }
  260. $levelName = static::getLevelName($level);
  261. $record = [
  262. 'message' => $message,
  263. 'context' => $context,
  264. 'level' => $level,
  265. 'level_name' => $levelName,
  266. 'channel' => $this->name,
  267. 'datetime' => new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  268. 'extra' => [],
  269. ];
  270. try {
  271. foreach ($this->processors as $processor) {
  272. $record = call_user_func($processor, $record);
  273. }
  274. // advance the array pointer to the first handler that will handle this record
  275. reset($this->handlers);
  276. while ($handlerKey !== key($this->handlers)) {
  277. next($this->handlers);
  278. }
  279. while ($handler = current($this->handlers)) {
  280. if (true === $handler->handle($record)) {
  281. break;
  282. }
  283. next($this->handlers);
  284. }
  285. } catch (Throwable $e) {
  286. $this->handleException($e, $record);
  287. }
  288. return true;
  289. }
  290. /**
  291. * Ends a log cycle and frees all resources used by handlers.
  292. *
  293. * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  294. * Handlers that have been closed should be able to accept log records again and re-open
  295. * themselves on demand, but this may not always be possible depending on implementation.
  296. *
  297. * This is useful at the end of a request and will be called automatically on every handler
  298. * when they get destructed.
  299. */
  300. public function close(): void
  301. {
  302. foreach ($this->handlers as $handler) {
  303. $handler->close();
  304. }
  305. }
  306. /**
  307. * Ends a log cycle and resets all handlers and processors to their initial state.
  308. *
  309. * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  310. * state, and getting it back to a state in which it can receive log records again.
  311. *
  312. * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  313. * have a long running process like a worker or an application server serving multiple requests
  314. * in one process.
  315. */
  316. public function reset(): void
  317. {
  318. foreach ($this->handlers as $handler) {
  319. if ($handler instanceof ResettableInterface) {
  320. $handler->reset();
  321. }
  322. }
  323. foreach ($this->processors as $processor) {
  324. if ($processor instanceof ResettableInterface) {
  325. $processor->reset();
  326. }
  327. }
  328. }
  329. /**
  330. * Gets all supported logging levels.
  331. *
  332. * @return array Assoc array with human-readable level names => level codes.
  333. */
  334. public static function getLevels(): array
  335. {
  336. return array_flip(static::$levels);
  337. }
  338. /**
  339. * Gets the name of the logging level.
  340. *
  341. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  342. */
  343. public static function getLevelName(int $level): string
  344. {
  345. if (!isset(static::$levels[$level])) {
  346. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  347. }
  348. return static::$levels[$level];
  349. }
  350. /**
  351. * Converts PSR-3 levels to Monolog ones if necessary
  352. *
  353. * @param string|int $level Level number (monolog) or name (PSR-3)
  354. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  355. */
  356. public static function toMonologLevel($level): int
  357. {
  358. if (is_string($level)) {
  359. if (defined(__CLASS__.'::'.strtoupper($level))) {
  360. return constant(__CLASS__.'::'.strtoupper($level));
  361. }
  362. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  363. }
  364. return $level;
  365. }
  366. /**
  367. * Checks whether the Logger has a handler that listens on the given level
  368. */
  369. public function isHandling(int $level): bool
  370. {
  371. $record = [
  372. 'level' => $level,
  373. ];
  374. foreach ($this->handlers as $handler) {
  375. if ($handler->isHandling($record)) {
  376. return true;
  377. }
  378. }
  379. return false;
  380. }
  381. /**
  382. * Set a custom exception handler that will be called if adding a new record fails
  383. *
  384. * The callable will receive an exception object and the record that failed to be logged
  385. */
  386. public function setExceptionHandler(?callable $callback): self
  387. {
  388. $this->exceptionHandler = $callback;
  389. return $this;
  390. }
  391. public function getExceptionHandler(): ?callable
  392. {
  393. return $this->exceptionHandler;
  394. }
  395. /**
  396. * Adds a log record at an arbitrary level.
  397. *
  398. * This method allows for compatibility with common interfaces.
  399. *
  400. * @param mixed $level The log level
  401. * @param string $message The log message
  402. * @param array $context The log context
  403. */
  404. public function log($level, $message, array $context = [])
  405. {
  406. $level = static::toMonologLevel($level);
  407. $this->addRecord($level, (string) $message, $context);
  408. }
  409. /**
  410. * Adds a log record at the DEBUG level.
  411. *
  412. * This method allows for compatibility with common interfaces.
  413. *
  414. * @param string $message The log message
  415. * @param array $context The log context
  416. */
  417. public function debug($message, array $context = [])
  418. {
  419. $this->addRecord(static::DEBUG, (string) $message, $context);
  420. }
  421. /**
  422. * Adds a log record at the INFO level.
  423. *
  424. * This method allows for compatibility with common interfaces.
  425. *
  426. * @param string $message The log message
  427. * @param array $context The log context
  428. */
  429. public function info($message, array $context = [])
  430. {
  431. $this->addRecord(static::INFO, (string) $message, $context);
  432. }
  433. /**
  434. * Adds a log record at the NOTICE level.
  435. *
  436. * This method allows for compatibility with common interfaces.
  437. *
  438. * @param string $message The log message
  439. * @param array $context The log context
  440. */
  441. public function notice($message, array $context = [])
  442. {
  443. $this->addRecord(static::NOTICE, (string) $message, $context);
  444. }
  445. /**
  446. * Adds a log record at the WARNING level.
  447. *
  448. * This method allows for compatibility with common interfaces.
  449. *
  450. * @param string $message The log message
  451. * @param array $context The log context
  452. */
  453. public function warning($message, array $context = [])
  454. {
  455. $this->addRecord(static::WARNING, (string) $message, $context);
  456. }
  457. /**
  458. * Adds a log record at the ERROR level.
  459. *
  460. * This method allows for compatibility with common interfaces.
  461. *
  462. * @param string $message The log message
  463. * @param array $context The log context
  464. */
  465. public function error($message, array $context = [])
  466. {
  467. $this->addRecord(static::ERROR, (string) $message, $context);
  468. }
  469. /**
  470. * Adds a log record at the CRITICAL level.
  471. *
  472. * This method allows for compatibility with common interfaces.
  473. *
  474. * @param string $message The log message
  475. * @param array $context The log context
  476. */
  477. public function critical($message, array $context = [])
  478. {
  479. $this->addRecord(static::CRITICAL, (string) $message, $context);
  480. }
  481. /**
  482. * Adds a log record at the ALERT level.
  483. *
  484. * This method allows for compatibility with common interfaces.
  485. *
  486. * @param string $message The log message
  487. * @param array $context The log context
  488. */
  489. public function alert($message, array $context = [])
  490. {
  491. $this->addRecord(static::ALERT, (string) $message, $context);
  492. }
  493. /**
  494. * Adds a log record at the EMERGENCY level.
  495. *
  496. * This method allows for compatibility with common interfaces.
  497. *
  498. * @param string $message The log message
  499. * @param array $context The log context
  500. */
  501. public function emergency($message, array $context = [])
  502. {
  503. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  504. }
  505. /**
  506. * Sets the timezone to be used for the timestamp of log records.
  507. */
  508. public function setTimezone(DateTimeZone $tz): self
  509. {
  510. $this->timezone = $tz;
  511. return $this;
  512. }
  513. /**
  514. * Returns the timezone to be used for the timestamp of log records.
  515. */
  516. public function getTimezone(): DateTimeZone
  517. {
  518. return $this->timezone;
  519. }
  520. /**
  521. * Delegates exception management to the custom exception handler,
  522. * or throws the exception if no custom handler is set.
  523. */
  524. protected function handleException(Throwable $e, array $record)
  525. {
  526. if (!$this->exceptionHandler) {
  527. throw $e;
  528. }
  529. call_user_func($this->exceptionHandler, $e, $record);
  530. }
  531. }