Logger.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. /**
  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 = 2;
  76. /**
  77. * Logging levels from syslog protocol defined in RFC 5424
  78. *
  79. * This is a static variable and not a constant to serve as an extension point for custom levels
  80. *
  81. * @var string[] $levels Logging levels with the levels as key
  82. */
  83. protected static $levels = [
  84. self::DEBUG => 'DEBUG',
  85. self::INFO => 'INFO',
  86. self::NOTICE => 'NOTICE',
  87. self::WARNING => 'WARNING',
  88. self::ERROR => 'ERROR',
  89. self::CRITICAL => 'CRITICAL',
  90. self::ALERT => 'ALERT',
  91. self::EMERGENCY => 'EMERGENCY',
  92. ];
  93. /**
  94. * @var string
  95. */
  96. protected $name;
  97. /**
  98. * The handler stack
  99. *
  100. * @var HandlerInterface[]
  101. */
  102. protected $handlers;
  103. /**
  104. * Processors that will process all log records
  105. *
  106. * To process records of a single handler instead, add the processor on that specific handler
  107. *
  108. * @var callable[]
  109. */
  110. protected $processors;
  111. /**
  112. * @var bool
  113. */
  114. protected $microsecondTimestamps = false;
  115. /**
  116. * @var DateTimeZone
  117. */
  118. protected $timezone;
  119. /**
  120. * @param string $name The logging channel, a simple descriptive name that is attached to all log records
  121. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  122. * @param callable[] $processors Optional array of processors
  123. * @param DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used
  124. */
  125. public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone $timezone = null)
  126. {
  127. $this->name = $name;
  128. $this->handlers = $handlers;
  129. $this->processors = $processors;
  130. $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  131. }
  132. public function getName(): string
  133. {
  134. return $this->name;
  135. }
  136. /**
  137. * Return a new cloned instance with the name changed
  138. */
  139. public function withName(string $name): self
  140. {
  141. $new = clone $this;
  142. $new->name = $name;
  143. return $new;
  144. }
  145. /**
  146. * Pushes a handler on to the stack.
  147. */
  148. public function pushHandler(HandlerInterface $handler): self
  149. {
  150. array_unshift($this->handlers, $handler);
  151. return $this;
  152. }
  153. /**
  154. * Pops a handler from the stack
  155. *
  156. * @throws \LogicException If empty handler stack
  157. */
  158. public function popHandler(): HandlerInterface
  159. {
  160. if (!$this->handlers) {
  161. throw new \LogicException('You tried to pop from an empty handler stack.');
  162. }
  163. return array_shift($this->handlers);
  164. }
  165. /**
  166. * Set handlers, replacing all existing ones.
  167. *
  168. * If a map is passed, keys will be ignored.
  169. *
  170. * @param HandlerInterface[] $handlers
  171. */
  172. public function setHandlers(array $handlers): self
  173. {
  174. $this->handlers = [];
  175. foreach (array_reverse($handlers) as $handler) {
  176. $this->pushHandler($handler);
  177. }
  178. return $this;
  179. }
  180. /**
  181. * @return HandlerInterface[]
  182. */
  183. public function getHandlers(): array
  184. {
  185. return $this->handlers;
  186. }
  187. /**
  188. * Adds a processor on to the stack.
  189. */
  190. public function pushProcessor(callable $callback): self
  191. {
  192. array_unshift($this->processors, $callback);
  193. return $this;
  194. }
  195. /**
  196. * Removes the processor on top of the stack and returns it.
  197. *
  198. * @throws \LogicException If empty processor stack
  199. * @return callable
  200. */
  201. public function popProcessor(): callable
  202. {
  203. if (!$this->processors) {
  204. throw new \LogicException('You tried to pop from an empty processor stack.');
  205. }
  206. return array_shift($this->processors);
  207. }
  208. /**
  209. * @return callable[]
  210. */
  211. public function getProcessors(): array
  212. {
  213. return $this->processors;
  214. }
  215. /**
  216. * Control the use of microsecond resolution timestamps in the 'datetime'
  217. * member of new records.
  218. *
  219. * Generating microsecond resolution timestamps by calling
  220. * microtime(true), formatting the result via sprintf() and then parsing
  221. * the resulting string via \DateTime::createFromFormat() can incur
  222. * a measurable runtime overhead vs simple usage of DateTime to capture
  223. * a second resolution timestamp in systems which generate a large number
  224. * of log events.
  225. *
  226. * @param bool $micro True to use microtime() to create timestamps
  227. */
  228. public function useMicrosecondTimestamps(bool $micro)
  229. {
  230. $this->microsecondTimestamps = $micro;
  231. }
  232. /**
  233. * Adds a log record.
  234. *
  235. * @param int $level The logging level
  236. * @param string $message The log message
  237. * @param array $context The log context
  238. * @return Boolean Whether the record has been processed
  239. */
  240. public function addRecord(int $level, string $message, array $context = []): bool
  241. {
  242. $levelName = static::getLevelName($level);
  243. // check if any handler will handle this message so we can return early and save cycles
  244. $handlerKey = null;
  245. reset($this->handlers);
  246. while ($handler = current($this->handlers)) {
  247. if ($handler->isHandling(['level' => $level])) {
  248. $handlerKey = key($this->handlers);
  249. break;
  250. }
  251. next($this->handlers);
  252. }
  253. if (null === $handlerKey) {
  254. return false;
  255. }
  256. $record = [
  257. 'message' => $message,
  258. 'context' => $context,
  259. 'level' => $level,
  260. 'level_name' => $levelName,
  261. 'channel' => $this->name,
  262. 'datetime' => new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  263. 'extra' => [],
  264. ];
  265. foreach ($this->processors as $processor) {
  266. $record = call_user_func($processor, $record);
  267. }
  268. while ($handler = current($this->handlers)) {
  269. if (true === $handler->handle($record)) {
  270. break;
  271. }
  272. next($this->handlers);
  273. }
  274. return true;
  275. }
  276. /**
  277. * Gets all supported logging levels.
  278. *
  279. * @return array Assoc array with human-readable level names => level codes.
  280. */
  281. public static function getLevels(): array
  282. {
  283. return array_flip(static::$levels);
  284. }
  285. /**
  286. * Gets the name of the logging level.
  287. *
  288. * @param int $level
  289. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  290. * @return string
  291. */
  292. public static function getLevelName(int $level): string
  293. {
  294. if (!isset(static::$levels[$level])) {
  295. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  296. }
  297. return static::$levels[$level];
  298. }
  299. /**
  300. * Converts PSR-3 levels to Monolog ones if necessary
  301. *
  302. * @param string|int Level number (monolog) or name (PSR-3)
  303. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  304. * @return int
  305. */
  306. public static function toMonologLevel($level): int
  307. {
  308. if (is_string($level)) {
  309. if (defined(__CLASS__.'::'.strtoupper($level))) {
  310. return constant(__CLASS__.'::'.strtoupper($level));
  311. }
  312. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  313. }
  314. return $level;
  315. }
  316. /**
  317. * Checks whether the Logger has a handler that listens on the given level
  318. *
  319. * @param int $level
  320. * @return Boolean
  321. */
  322. public function isHandling(int $level): bool
  323. {
  324. $record = [
  325. 'level' => $level,
  326. ];
  327. foreach ($this->handlers as $handler) {
  328. if ($handler->isHandling($record)) {
  329. return true;
  330. }
  331. }
  332. return false;
  333. }
  334. /**
  335. * Adds a log record at an arbitrary level.
  336. *
  337. * This method allows for compatibility with common interfaces.
  338. *
  339. * @param mixed $level The log level
  340. * @param string $message The log message
  341. * @param array $context The log context
  342. */
  343. public function log($level, $message, array $context = [])
  344. {
  345. $level = static::toMonologLevel($level);
  346. $this->addRecord($level, (string) $message, $context);
  347. }
  348. /**
  349. * Adds a log record at the DEBUG level.
  350. *
  351. * This method allows for compatibility with common interfaces.
  352. *
  353. * @param string $message The log message
  354. * @param array $context The log context
  355. */
  356. public function debug($message, array $context = [])
  357. {
  358. $this->addRecord(static::DEBUG, (string) $message, $context);
  359. }
  360. /**
  361. * Adds a log record at the INFO level.
  362. *
  363. * This method allows for compatibility with common interfaces.
  364. *
  365. * @param string $message The log message
  366. * @param array $context The log context
  367. */
  368. public function info($message, array $context = [])
  369. {
  370. $this->addRecord(static::INFO, (string) $message, $context);
  371. }
  372. /**
  373. * Adds a log record at the NOTICE level.
  374. *
  375. * This method allows for compatibility with common interfaces.
  376. *
  377. * @param string $message The log message
  378. * @param array $context The log context
  379. */
  380. public function notice($message, array $context = [])
  381. {
  382. $this->addRecord(static::NOTICE, (string) $message, $context);
  383. }
  384. /**
  385. * Adds a log record at the WARNING level.
  386. *
  387. * This method allows for compatibility with common interfaces.
  388. *
  389. * @param string $message The log message
  390. * @param array $context The log context
  391. */
  392. public function warning($message, array $context = [])
  393. {
  394. $this->addRecord(static::WARNING, (string) $message, $context);
  395. }
  396. /**
  397. * Adds a log record at the ERROR level.
  398. *
  399. * This method allows for compatibility with common interfaces.
  400. *
  401. * @param string $message The log message
  402. * @param array $context The log context
  403. */
  404. public function error($message, array $context = [])
  405. {
  406. $this->addRecord(static::ERROR, (string) $message, $context);
  407. }
  408. /**
  409. * Adds a log record at the CRITICAL level.
  410. *
  411. * This method allows for compatibility with common interfaces.
  412. *
  413. * @param string $message The log message
  414. * @param array $context The log context
  415. */
  416. public function critical($message, array $context = [])
  417. {
  418. $this->addRecord(static::CRITICAL, (string) $message, $context);
  419. }
  420. /**
  421. * Adds a log record at the ALERT level.
  422. *
  423. * This method allows for compatibility with common interfaces.
  424. *
  425. * @param string $message The log message
  426. * @param array $context The log context
  427. */
  428. public function alert($message, array $context = [])
  429. {
  430. $this->addRecord(static::ALERT, (string) $message, $context);
  431. }
  432. /**
  433. * Adds a log record at the EMERGENCY level.
  434. *
  435. * This method allows for compatibility with common interfaces.
  436. *
  437. * @param string $message The log message
  438. * @param array $context The log context
  439. */
  440. public function emergency($message, array $context = [])
  441. {
  442. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  443. }
  444. /**
  445. * Set the timezone to be used for the timestamp of log records.
  446. *
  447. * @param DateTimeZone $tz Timezone object
  448. */
  449. public function setTimezone(DateTimeZone $tz): self
  450. {
  451. $this->timezone = $tz;
  452. return $this;
  453. }
  454. /**
  455. * Set the timezone to be used for the timestamp of log records.
  456. *
  457. * @return DateTimeZone
  458. */
  459. public function getTimezone(): DateTimeZone
  460. {
  461. return $this->timezone;
  462. }
  463. }