Logger.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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
  25. {
  26. /**
  27. * Detailed debug information
  28. */
  29. const DEBUG = 100;
  30. /**
  31. * Interesting events
  32. *
  33. * Examples: User logs in, SQL logs.
  34. */
  35. const INFO = 200;
  36. /**
  37. * Uncommon events
  38. */
  39. 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. const WARNING = 300;
  47. /**
  48. * Runtime errors
  49. */
  50. const ERROR = 400;
  51. /**
  52. * Critical conditions
  53. *
  54. * Example: Application component unavailable, unexpected exception.
  55. */
  56. 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. const ALERT = 550;
  64. /**
  65. * Urgent alert.
  66. */
  67. 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. 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
  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. * Gets all supported logging levels.
  292. *
  293. * @return array Assoc array with human-readable level names => level codes.
  294. */
  295. public static function getLevels(): array
  296. {
  297. return array_flip(static::$levels);
  298. }
  299. /**
  300. * Gets the name of the logging level.
  301. *
  302. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  303. */
  304. public static function getLevelName(int $level): string
  305. {
  306. if (!isset(static::$levels[$level])) {
  307. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  308. }
  309. return static::$levels[$level];
  310. }
  311. /**
  312. * Converts PSR-3 levels to Monolog ones if necessary
  313. *
  314. * @param string|int Level number (monolog) or name (PSR-3)
  315. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  316. */
  317. public static function toMonologLevel($level): int
  318. {
  319. if (is_string($level)) {
  320. if (defined(__CLASS__.'::'.strtoupper($level))) {
  321. return constant(__CLASS__.'::'.strtoupper($level));
  322. }
  323. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  324. }
  325. return $level;
  326. }
  327. /**
  328. * Checks whether the Logger has a handler that listens on the given level
  329. */
  330. public function isHandling(int $level): bool
  331. {
  332. $record = [
  333. 'level' => $level,
  334. ];
  335. foreach ($this->handlers as $handler) {
  336. if ($handler->isHandling($record)) {
  337. return true;
  338. }
  339. }
  340. return false;
  341. }
  342. /**
  343. * Set a custom exception handler that will be called if adding a new record fails
  344. *
  345. * The callable will receive an exception object and the record that failed to be logged
  346. */
  347. public function setExceptionHandler(?callable $callback): self
  348. {
  349. $this->exceptionHandler = $callback;
  350. return $this;
  351. }
  352. public function getExceptionHandler(): ?callable
  353. {
  354. return $this->exceptionHandler;
  355. }
  356. /**
  357. * Adds a log record at an arbitrary level.
  358. *
  359. * This method allows for compatibility with common interfaces.
  360. *
  361. * @param mixed $level The log level
  362. * @param string $message The log message
  363. * @param array $context The log context
  364. */
  365. public function log($level, $message, array $context = [])
  366. {
  367. $level = static::toMonologLevel($level);
  368. $this->addRecord($level, (string) $message, $context);
  369. }
  370. /**
  371. * Adds a log record at the DEBUG level.
  372. *
  373. * This method allows for compatibility with common interfaces.
  374. *
  375. * @param string $message The log message
  376. * @param array $context The log context
  377. */
  378. public function debug($message, array $context = [])
  379. {
  380. $this->addRecord(static::DEBUG, (string) $message, $context);
  381. }
  382. /**
  383. * Adds a log record at the INFO level.
  384. *
  385. * This method allows for compatibility with common interfaces.
  386. *
  387. * @param string $message The log message
  388. * @param array $context The log context
  389. */
  390. public function info($message, array $context = [])
  391. {
  392. $this->addRecord(static::INFO, (string) $message, $context);
  393. }
  394. /**
  395. * Adds a log record at the NOTICE level.
  396. *
  397. * This method allows for compatibility with common interfaces.
  398. *
  399. * @param string $message The log message
  400. * @param array $context The log context
  401. */
  402. public function notice($message, array $context = [])
  403. {
  404. $this->addRecord(static::NOTICE, (string) $message, $context);
  405. }
  406. /**
  407. * Adds a log record at the WARNING level.
  408. *
  409. * This method allows for compatibility with common interfaces.
  410. *
  411. * @param string $message The log message
  412. * @param array $context The log context
  413. */
  414. public function warning($message, array $context = [])
  415. {
  416. $this->addRecord(static::WARNING, (string) $message, $context);
  417. }
  418. /**
  419. * Adds a log record at the ERROR level.
  420. *
  421. * This method allows for compatibility with common interfaces.
  422. *
  423. * @param string $message The log message
  424. * @param array $context The log context
  425. */
  426. public function error($message, array $context = [])
  427. {
  428. $this->addRecord(static::ERROR, (string) $message, $context);
  429. }
  430. /**
  431. * Adds a log record at the CRITICAL level.
  432. *
  433. * This method allows for compatibility with common interfaces.
  434. *
  435. * @param string $message The log message
  436. * @param array $context The log context
  437. */
  438. public function critical($message, array $context = [])
  439. {
  440. $this->addRecord(static::CRITICAL, (string) $message, $context);
  441. }
  442. /**
  443. * Adds a log record at the ALERT level.
  444. *
  445. * This method allows for compatibility with common interfaces.
  446. *
  447. * @param string $message The log message
  448. * @param array $context The log context
  449. */
  450. public function alert($message, array $context = [])
  451. {
  452. $this->addRecord(static::ALERT, (string) $message, $context);
  453. }
  454. /**
  455. * Adds a log record at the EMERGENCY level.
  456. *
  457. * This method allows for compatibility with common interfaces.
  458. *
  459. * @param string $message The log message
  460. * @param array $context The log context
  461. */
  462. public function emergency($message, array $context = [])
  463. {
  464. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  465. }
  466. /**
  467. * Sets the timezone to be used for the timestamp of log records.
  468. */
  469. public function setTimezone(DateTimeZone $tz): self
  470. {
  471. $this->timezone = $tz;
  472. return $this;
  473. }
  474. /**
  475. * Returns the timezone to be used for the timestamp of log records.
  476. */
  477. public function getTimezone(): DateTimeZone
  478. {
  479. return $this->timezone;
  480. }
  481. /**
  482. * Delegates exception management to the custom exception handler,
  483. * or throws the exception if no custom handler is set.
  484. */
  485. protected function handleException(Throwable $e, array $record)
  486. {
  487. if (!$this->exceptionHandler) {
  488. throw $e;
  489. }
  490. call_user_func($this->exceptionHandler, $e, $record);
  491. }
  492. }