Logger.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. <?php
  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 Monolog\Handler\HandlerInterface;
  12. use Monolog\Handler\StreamHandler;
  13. use Psr\Log\LoggerInterface;
  14. use Psr\Log\InvalidArgumentException;
  15. /**
  16. * Monolog log channel
  17. *
  18. * It contains a stack of Handlers and a stack of Processors,
  19. * and uses them to store records that are added to it.
  20. *
  21. * @author Jordi Boggiano <j.boggiano@seld.be>
  22. */
  23. class Logger implements LoggerInterface
  24. {
  25. /**
  26. * Detailed debug information
  27. */
  28. const DEBUG = 100;
  29. /**
  30. * Interesting events
  31. *
  32. * Examples: User logs in, SQL logs.
  33. */
  34. const INFO = 200;
  35. /**
  36. * Uncommon events
  37. */
  38. const NOTICE = 250;
  39. /**
  40. * Exceptional occurrences that are not errors
  41. *
  42. * Examples: Use of deprecated APIs, poor use of an API,
  43. * undesirable things that are not necessarily wrong.
  44. */
  45. const WARNING = 300;
  46. /**
  47. * Runtime errors
  48. */
  49. const ERROR = 400;
  50. /**
  51. * Critical conditions
  52. *
  53. * Example: Application component unavailable, unexpected exception.
  54. */
  55. const CRITICAL = 500;
  56. /**
  57. * Action must be taken immediately
  58. *
  59. * Example: Entire website down, database unavailable, etc.
  60. * This should trigger the SMS alerts and wake you up.
  61. */
  62. const ALERT = 550;
  63. /**
  64. * Urgent alert.
  65. */
  66. const EMERGENCY = 600;
  67. /**
  68. * Monolog API version
  69. *
  70. * This is only bumped when API breaks are done and should
  71. * follow the major version of the library
  72. *
  73. * @var int
  74. */
  75. const API = 1;
  76. /**
  77. * Logging levels from syslog protocol defined in RFC 5424
  78. *
  79. * @var array $levels Logging levels
  80. */
  81. protected static $levels = array(
  82. self::DEBUG => 'DEBUG',
  83. self::INFO => 'INFO',
  84. self::NOTICE => 'NOTICE',
  85. self::WARNING => 'WARNING',
  86. self::ERROR => 'ERROR',
  87. self::CRITICAL => 'CRITICAL',
  88. self::ALERT => 'ALERT',
  89. self::EMERGENCY => 'EMERGENCY',
  90. );
  91. /**
  92. * @var \DateTimeZone
  93. */
  94. protected static $timezone;
  95. /**
  96. * @var string
  97. */
  98. protected $name;
  99. /**
  100. * The handler stack
  101. *
  102. * @var HandlerInterface[]
  103. */
  104. protected $handlers;
  105. /**
  106. * Processors that will process all log records
  107. *
  108. * To process records of a single handler instead, add the processor on that specific handler
  109. *
  110. * @var callable[]
  111. */
  112. protected $processors;
  113. /**
  114. * @var bool
  115. */
  116. protected $microsecondTimestamps = true;
  117. /**
  118. * @param string $name The logging channel
  119. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  120. * @param callable[] $processors Optional array of processors
  121. */
  122. public function __construct($name, array $handlers = array(), array $processors = array())
  123. {
  124. $this->name = $name;
  125. $this->handlers = $handlers;
  126. $this->processors = $processors;
  127. }
  128. /**
  129. * @return string
  130. */
  131. public function getName()
  132. {
  133. return $this->name;
  134. }
  135. /**
  136. * Return a new cloned instance with the name changed
  137. *
  138. * @return static
  139. */
  140. public function withName($name)
  141. {
  142. $new = clone $this;
  143. $new->name = $name;
  144. return $new;
  145. }
  146. /**
  147. * Pushes a handler on to the stack.
  148. *
  149. * @param HandlerInterface $handler
  150. * @return $this
  151. */
  152. public function pushHandler(HandlerInterface $handler)
  153. {
  154. array_unshift($this->handlers, $handler);
  155. return $this;
  156. }
  157. /**
  158. * Pops a handler from the stack
  159. *
  160. * @return HandlerInterface
  161. */
  162. public function popHandler()
  163. {
  164. if (!$this->handlers) {
  165. throw new \LogicException('You tried to pop from an empty handler stack.');
  166. }
  167. return array_shift($this->handlers);
  168. }
  169. /**
  170. * Set handlers, replacing all existing ones.
  171. *
  172. * If a map is passed, keys will be ignored.
  173. *
  174. * @param HandlerInterface[] $handlers
  175. * @return $this
  176. */
  177. public function setHandlers(array $handlers)
  178. {
  179. $this->handlers = array();
  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()
  189. {
  190. return $this->handlers;
  191. }
  192. /**
  193. * Adds a processor on to the stack.
  194. *
  195. * @param callable $callback
  196. * @return $this
  197. */
  198. public function pushProcessor($callback)
  199. {
  200. if (!is_callable($callback)) {
  201. throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
  202. }
  203. array_unshift($this->processors, $callback);
  204. return $this;
  205. }
  206. /**
  207. * Removes the processor on top of the stack and returns it.
  208. *
  209. * @return callable
  210. */
  211. public function popProcessor()
  212. {
  213. if (!$this->processors) {
  214. throw new \LogicException('You tried to pop from an empty processor stack.');
  215. }
  216. return array_shift($this->processors);
  217. }
  218. /**
  219. * @return callable[]
  220. */
  221. public function getProcessors()
  222. {
  223. return $this->processors;
  224. }
  225. /**
  226. * Control the use of microsecond resolution timestamps in the 'datetime'
  227. * member of new records.
  228. *
  229. * Generating microsecond resolution timestamps by calling
  230. * microtime(true), formatting the result via sprintf() and then parsing
  231. * the resulting string via \DateTime::createFromFormat() can incur
  232. * a measurable runtime overhead vs simple usage of DateTime to capture
  233. * a second resolution timestamp in systems which generate a large number
  234. * of log events.
  235. *
  236. * @param bool $micro True to use microtime() to create timestamps
  237. */
  238. public function useMicrosecondTimestamps($micro)
  239. {
  240. $this->microsecondTimestamps = (bool) $micro;
  241. }
  242. /**
  243. * Adds a log record.
  244. *
  245. * @param int $level The logging level
  246. * @param string $message The log message
  247. * @param array $context The log context
  248. * @return Boolean Whether the record has been processed
  249. */
  250. public function addRecord($level, $message, array $context = array())
  251. {
  252. if (!$this->handlers) {
  253. $this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
  254. }
  255. $levelName = static::getLevelName($level);
  256. // check if any handler will handle this message so we can return early and save cycles
  257. $handlerKey = null;
  258. reset($this->handlers);
  259. while ($handler = current($this->handlers)) {
  260. if ($handler->isHandling(array('level' => $level))) {
  261. $handlerKey = key($this->handlers);
  262. break;
  263. }
  264. next($this->handlers);
  265. }
  266. if (null === $handlerKey) {
  267. return false;
  268. }
  269. if (!static::$timezone) {
  270. static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC');
  271. }
  272. // php7.1+ always has microseconds enabled, so we do not need this hack
  273. if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) {
  274. $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone);
  275. } else {
  276. $ts = new \DateTime(null, static::$timezone);
  277. }
  278. $ts->setTimezone(static::$timezone);
  279. $record = array(
  280. 'message' => (string) $message,
  281. 'context' => $context,
  282. 'level' => $level,
  283. 'level_name' => $levelName,
  284. 'channel' => $this->name,
  285. 'datetime' => $ts,
  286. 'extra' => array(),
  287. );
  288. foreach ($this->processors as $processor) {
  289. $record = call_user_func($processor, $record);
  290. }
  291. while ($handler = current($this->handlers)) {
  292. if (true === $handler->handle($record)) {
  293. break;
  294. }
  295. next($this->handlers);
  296. }
  297. return true;
  298. }
  299. /**
  300. * Adds a log record at the DEBUG level.
  301. *
  302. * @param string $message The log message
  303. * @param array $context The log context
  304. * @return Boolean Whether the record has been processed
  305. */
  306. public function addDebug($message, array $context = array())
  307. {
  308. return $this->addRecord(static::DEBUG, $message, $context);
  309. }
  310. /**
  311. * Adds a log record at the INFO level.
  312. *
  313. * @param string $message The log message
  314. * @param array $context The log context
  315. * @return Boolean Whether the record has been processed
  316. */
  317. public function addInfo($message, array $context = array())
  318. {
  319. return $this->addRecord(static::INFO, $message, $context);
  320. }
  321. /**
  322. * Adds a log record at the NOTICE level.
  323. *
  324. * @param string $message The log message
  325. * @param array $context The log context
  326. * @return Boolean Whether the record has been processed
  327. */
  328. public function addNotice($message, array $context = array())
  329. {
  330. return $this->addRecord(static::NOTICE, $message, $context);
  331. }
  332. /**
  333. * Adds a log record at the WARNING level.
  334. *
  335. * @param string $message The log message
  336. * @param array $context The log context
  337. * @return Boolean Whether the record has been processed
  338. */
  339. public function addWarning($message, array $context = array())
  340. {
  341. return $this->addRecord(static::WARNING, $message, $context);
  342. }
  343. /**
  344. * Adds a log record at the ERROR level.
  345. *
  346. * @param string $message The log message
  347. * @param array $context The log context
  348. * @return Boolean Whether the record has been processed
  349. */
  350. public function addError($message, array $context = array())
  351. {
  352. return $this->addRecord(static::ERROR, $message, $context);
  353. }
  354. /**
  355. * Adds a log record at the CRITICAL level.
  356. *
  357. * @param string $message The log message
  358. * @param array $context The log context
  359. * @return Boolean Whether the record has been processed
  360. */
  361. public function addCritical($message, array $context = array())
  362. {
  363. return $this->addRecord(static::CRITICAL, $message, $context);
  364. }
  365. /**
  366. * Adds a log record at the ALERT level.
  367. *
  368. * @param string $message The log message
  369. * @param array $context The log context
  370. * @return Boolean Whether the record has been processed
  371. */
  372. public function addAlert($message, array $context = array())
  373. {
  374. return $this->addRecord(static::ALERT, $message, $context);
  375. }
  376. /**
  377. * Adds a log record at the EMERGENCY level.
  378. *
  379. * @param string $message The log message
  380. * @param array $context The log context
  381. * @return Boolean Whether the record has been processed
  382. */
  383. public function addEmergency($message, array $context = array())
  384. {
  385. return $this->addRecord(static::EMERGENCY, $message, $context);
  386. }
  387. /**
  388. * Gets all supported logging levels.
  389. *
  390. * @return array Assoc array with human-readable level names => level codes.
  391. */
  392. public static function getLevels()
  393. {
  394. return array_flip(static::$levels);
  395. }
  396. /**
  397. * Gets the name of the logging level.
  398. *
  399. * @param int $level
  400. * @return string
  401. */
  402. public static function getLevelName($level)
  403. {
  404. if (!isset(static::$levels[$level])) {
  405. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  406. }
  407. return static::$levels[$level];
  408. }
  409. /**
  410. * Converts PSR-3 levels to Monolog ones if necessary
  411. *
  412. * @param string|int Level number (monolog) or name (PSR-3)
  413. * @return int
  414. */
  415. public static function toMonologLevel($level)
  416. {
  417. if (is_string($level) && defined(__CLASS__.'::'.strtoupper($level))) {
  418. return constant(__CLASS__.'::'.strtoupper($level));
  419. }
  420. return $level;
  421. }
  422. /**
  423. * Checks whether the Logger has a handler that listens on the given level
  424. *
  425. * @param int $level
  426. * @return Boolean
  427. */
  428. public function isHandling($level)
  429. {
  430. $record = array(
  431. 'level' => $level,
  432. );
  433. foreach ($this->handlers as $handler) {
  434. if ($handler->isHandling($record)) {
  435. return true;
  436. }
  437. }
  438. return false;
  439. }
  440. /**
  441. * Adds a log record at an arbitrary level.
  442. *
  443. * This method allows for compatibility with common interfaces.
  444. *
  445. * @param mixed $level The log level
  446. * @param string $message The log message
  447. * @param array $context The log context
  448. * @return Boolean Whether the record has been processed
  449. */
  450. public function log($level, $message, array $context = array())
  451. {
  452. $level = static::toMonologLevel($level);
  453. return $this->addRecord($level, $message, $context);
  454. }
  455. /**
  456. * Adds a log record at the DEBUG level.
  457. *
  458. * This method allows for compatibility with common interfaces.
  459. *
  460. * @param string $message The log message
  461. * @param array $context The log context
  462. * @return Boolean Whether the record has been processed
  463. */
  464. public function debug($message, array $context = array())
  465. {
  466. return $this->addRecord(static::DEBUG, $message, $context);
  467. }
  468. /**
  469. * Adds a log record at the INFO level.
  470. *
  471. * This method allows for compatibility with common interfaces.
  472. *
  473. * @param string $message The log message
  474. * @param array $context The log context
  475. * @return Boolean Whether the record has been processed
  476. */
  477. public function info($message, array $context = array())
  478. {
  479. return $this->addRecord(static::INFO, $message, $context);
  480. }
  481. /**
  482. * Adds a log record at the NOTICE 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. * @return Boolean Whether the record has been processed
  489. */
  490. public function notice($message, array $context = array())
  491. {
  492. return $this->addRecord(static::NOTICE, $message, $context);
  493. }
  494. /**
  495. * Adds a log record at the WARNING level.
  496. *
  497. * This method allows for compatibility with common interfaces.
  498. *
  499. * @param string $message The log message
  500. * @param array $context The log context
  501. * @return Boolean Whether the record has been processed
  502. */
  503. public function warn($message, array $context = array())
  504. {
  505. return $this->addRecord(static::WARNING, $message, $context);
  506. }
  507. /**
  508. * Adds a log record at the WARNING level.
  509. *
  510. * This method allows for compatibility with common interfaces.
  511. *
  512. * @param string $message The log message
  513. * @param array $context The log context
  514. * @return Boolean Whether the record has been processed
  515. */
  516. public function warning($message, array $context = array())
  517. {
  518. return $this->addRecord(static::WARNING, $message, $context);
  519. }
  520. /**
  521. * Adds a log record at the ERROR level.
  522. *
  523. * This method allows for compatibility with common interfaces.
  524. *
  525. * @param string $message The log message
  526. * @param array $context The log context
  527. * @return Boolean Whether the record has been processed
  528. */
  529. public function err($message, array $context = array())
  530. {
  531. return $this->addRecord(static::ERROR, $message, $context);
  532. }
  533. /**
  534. * Adds a log record at the ERROR level.
  535. *
  536. * This method allows for compatibility with common interfaces.
  537. *
  538. * @param string $message The log message
  539. * @param array $context The log context
  540. * @return Boolean Whether the record has been processed
  541. */
  542. public function error($message, array $context = array())
  543. {
  544. return $this->addRecord(static::ERROR, $message, $context);
  545. }
  546. /**
  547. * Adds a log record at the CRITICAL level.
  548. *
  549. * This method allows for compatibility with common interfaces.
  550. *
  551. * @param string $message The log message
  552. * @param array $context The log context
  553. * @return Boolean Whether the record has been processed
  554. */
  555. public function crit($message, array $context = array())
  556. {
  557. return $this->addRecord(static::CRITICAL, $message, $context);
  558. }
  559. /**
  560. * Adds a log record at the CRITICAL level.
  561. *
  562. * This method allows for compatibility with common interfaces.
  563. *
  564. * @param string $message The log message
  565. * @param array $context The log context
  566. * @return Boolean Whether the record has been processed
  567. */
  568. public function critical($message, array $context = array())
  569. {
  570. return $this->addRecord(static::CRITICAL, $message, $context);
  571. }
  572. /**
  573. * Adds a log record at the ALERT level.
  574. *
  575. * This method allows for compatibility with common interfaces.
  576. *
  577. * @param string $message The log message
  578. * @param array $context The log context
  579. * @return Boolean Whether the record has been processed
  580. */
  581. public function alert($message, array $context = array())
  582. {
  583. return $this->addRecord(static::ALERT, $message, $context);
  584. }
  585. /**
  586. * Adds a log record at the EMERGENCY level.
  587. *
  588. * This method allows for compatibility with common interfaces.
  589. *
  590. * @param string $message The log message
  591. * @param array $context The log context
  592. * @return Boolean Whether the record has been processed
  593. */
  594. public function emerg($message, array $context = array())
  595. {
  596. return $this->addRecord(static::EMERGENCY, $message, $context);
  597. }
  598. /**
  599. * Adds a log record at the EMERGENCY level.
  600. *
  601. * This method allows for compatibility with common interfaces.
  602. *
  603. * @param string $message The log message
  604. * @param array $context The log context
  605. * @return Boolean Whether the record has been processed
  606. */
  607. public function emergency($message, array $context = array())
  608. {
  609. return $this->addRecord(static::EMERGENCY, $message, $context);
  610. }
  611. /**
  612. * Set the timezone to be used for the timestamp of log records.
  613. *
  614. * This is stored globally for all Logger instances
  615. *
  616. * @param \DateTimeZone $tz Timezone object
  617. */
  618. public static function setTimezone(\DateTimeZone $tz)
  619. {
  620. self::$timezone = $tz;
  621. }
  622. }