LogManager.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. <?php
  2. namespace Illuminate\Log;
  3. use Closure;
  4. use Throwable;
  5. use Illuminate\Support\Str;
  6. use Psr\Log\LoggerInterface;
  7. use InvalidArgumentException;
  8. use Monolog\Logger as Monolog;
  9. use Monolog\Handler\StreamHandler;
  10. use Monolog\Handler\SyslogHandler;
  11. use Monolog\Formatter\LineFormatter;
  12. use Monolog\Handler\ErrorLogHandler;
  13. use Monolog\Handler\HandlerInterface;
  14. use Monolog\Handler\RotatingFileHandler;
  15. use Monolog\Handler\SlackWebhookHandler;
  16. class LogManager implements LoggerInterface
  17. {
  18. /**
  19. * The application instance.
  20. *
  21. * @var \Illuminate\Foundation\Application
  22. */
  23. protected $app;
  24. /**
  25. * The array of resolved channels.
  26. *
  27. * @var array
  28. */
  29. protected $channels = [];
  30. /**
  31. * The registered custom driver creators.
  32. *
  33. * @var array
  34. */
  35. protected $customCreators = [];
  36. /**
  37. * The Log levels.
  38. *
  39. * @var array
  40. */
  41. protected $levels = [
  42. 'debug' => Monolog::DEBUG,
  43. 'info' => Monolog::INFO,
  44. 'notice' => Monolog::NOTICE,
  45. 'warning' => Monolog::WARNING,
  46. 'error' => Monolog::ERROR,
  47. 'critical' => Monolog::CRITICAL,
  48. 'alert' => Monolog::ALERT,
  49. 'emergency' => Monolog::EMERGENCY,
  50. ];
  51. /**
  52. * Create a new Log manager instance.
  53. *
  54. * @param \Illuminate\Foundation\Application $app
  55. * @return void
  56. */
  57. public function __construct($app)
  58. {
  59. $this->app = $app;
  60. }
  61. /**
  62. * Create a new, on-demand aggregate logger instance.
  63. *
  64. * @param array $channels
  65. * @param string|null $channel
  66. * @return \Psr\Log\LoggerInterface
  67. */
  68. public function stack(array $channels, $channel = null)
  69. {
  70. return new Logger(
  71. $this->createStackDriver(compact('channels', 'channel')),
  72. $this->app['events']
  73. );
  74. }
  75. /**
  76. * Get a log channel instance.
  77. *
  78. * @param string|null $channel
  79. * @return mixed
  80. */
  81. public function channel($channel = null)
  82. {
  83. return $this->driver($channel);
  84. }
  85. /**
  86. * Get a log driver instance.
  87. *
  88. * @param string|null $driver
  89. * @return mixed
  90. */
  91. public function driver($driver = null)
  92. {
  93. return $this->get($driver ?? $this->getDefaultDriver());
  94. }
  95. /**
  96. * Attempt to get the log from the local cache.
  97. *
  98. * @param string $name
  99. * @return \Psr\Log\LoggerInterface
  100. */
  101. protected function get($name)
  102. {
  103. try {
  104. return $this->channels[$name] ?? with($this->resolve($name), function ($logger) use ($name) {
  105. return $this->channels[$name] = $this->tap($name, new Logger($logger, $this->app['events']));
  106. });
  107. } catch (Throwable $e) {
  108. return tap($this->createEmergencyLogger(), function ($logger) use ($e) {
  109. $logger->emergency('Unable to create configured logger. Using emergency logger.', [
  110. 'exception' => $e,
  111. ]);
  112. });
  113. }
  114. }
  115. /**
  116. * Apply the configured taps for the logger.
  117. *
  118. * @param string $name
  119. * @param \Illuminate\Log\Logger $logger
  120. * @return \Illuminate\Log\Logger
  121. */
  122. protected function tap($name, Logger $logger)
  123. {
  124. foreach ($this->configurationFor($name)['tap'] ?? [] as $tap) {
  125. list($class, $arguments) = $this->parseTap($tap);
  126. $this->app->make($class)->__invoke($logger, ...explode(',', $arguments));
  127. }
  128. return $logger;
  129. }
  130. /**
  131. * Parse the given tap class string into a class name and arguments string.
  132. *
  133. * @param string $tap
  134. * @return array
  135. */
  136. protected function parseTap($tap)
  137. {
  138. return Str::contains($tap, ':') ? explode(':', $tap, 2) : [$tap, ''];
  139. }
  140. /**
  141. * Create an emergency log handler to avoid white screens of death.
  142. *
  143. * @return \Psr\Log\LoggerInterface
  144. */
  145. protected function createEmergencyLogger()
  146. {
  147. return new Logger(new Monolog('laravel', $this->prepareHandlers([new StreamHandler(
  148. $this->app->storagePath().'/logs/laravel.log', $this->level(['level' => 'debug'])
  149. )])), $this->app['events']);
  150. }
  151. /**
  152. * Resolve the given log instance by name.
  153. *
  154. * @param string $name
  155. * @return \Psr\Log\LoggerInterface
  156. *
  157. * @throws \InvalidArgumentException
  158. */
  159. protected function resolve($name)
  160. {
  161. $config = $this->configurationFor($name);
  162. if (is_null($config)) {
  163. throw new InvalidArgumentException("Log [{$name}] is not defined.");
  164. }
  165. if (isset($this->customCreators[$config['driver']])) {
  166. return $this->callCustomCreator($config);
  167. }
  168. $driverMethod = 'create'.ucfirst($config['driver']).'Driver';
  169. if (method_exists($this, $driverMethod)) {
  170. return $this->{$driverMethod}($config);
  171. }
  172. throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported.");
  173. }
  174. /**
  175. * Call a custom driver creator.
  176. *
  177. * @param array $config
  178. * @return mixed
  179. */
  180. protected function callCustomCreator(array $config)
  181. {
  182. return $this->customCreators[$config['driver']]($this->app, $config);
  183. }
  184. /**
  185. * Create a custom log driver instance.
  186. *
  187. * @param array $config
  188. * @return \Psr\Log\LoggerInterface
  189. */
  190. protected function createCustomDriver(array $config)
  191. {
  192. $factory = is_callable($via = $config['via']) ? $via : $this->app->make($via);
  193. return $factory($config);
  194. }
  195. /**
  196. * Create an aggregate log driver instance.
  197. *
  198. * @param array $config
  199. * @return \Psr\Log\LoggerInterface
  200. */
  201. protected function createStackDriver(array $config)
  202. {
  203. $handlers = collect($config['channels'])->flatMap(function ($channel) {
  204. return $this->channel($channel)->getHandlers();
  205. })->all();
  206. return new Monolog($this->parseChannel($config), $handlers);
  207. }
  208. /**
  209. * Create an instance of the single file log driver.
  210. *
  211. * @param array $config
  212. * @return \Psr\Log\LoggerInterface
  213. */
  214. protected function createSingleDriver(array $config)
  215. {
  216. return new Monolog($this->parseChannel($config), [
  217. $this->prepareHandler(
  218. new StreamHandler(
  219. $config['path'], $this->level($config),
  220. $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false
  221. )
  222. ),
  223. ]);
  224. }
  225. /**
  226. * Create an instance of the daily file log driver.
  227. *
  228. * @param array $config
  229. * @return \Psr\Log\LoggerInterface
  230. */
  231. protected function createDailyDriver(array $config)
  232. {
  233. return new Monolog($this->parseChannel($config), [
  234. $this->prepareHandler(new RotatingFileHandler(
  235. $config['path'], $config['days'] ?? 7, $this->level($config),
  236. $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false
  237. )),
  238. ]);
  239. }
  240. /**
  241. * Create an instance of the Slack log driver.
  242. *
  243. * @param array $config
  244. * @return \Psr\Log\LoggerInterface
  245. */
  246. protected function createSlackDriver(array $config)
  247. {
  248. return new Monolog($this->parseChannel($config), [
  249. $this->prepareHandler(new SlackWebhookHandler(
  250. $config['url'],
  251. $config['channel'] ?? null,
  252. $config['username'] ?? 'Laravel',
  253. $config['attachment'] ?? true,
  254. $config['emoji'] ?? ':boom:',
  255. $config['short'] ?? false,
  256. $config['context'] ?? true,
  257. $this->level($config)
  258. )),
  259. ]);
  260. }
  261. /**
  262. * Create an instance of the syslog log driver.
  263. *
  264. * @param array $config
  265. * @return \Psr\Log\LoggerInterface
  266. */
  267. protected function createSyslogDriver(array $config)
  268. {
  269. return new Monolog($this->parseChannel($config), [
  270. $this->prepareHandler(new SyslogHandler(
  271. $this->app['config']['app.name'], $config['facility'] ?? LOG_USER, $this->level($config))
  272. ),
  273. ]);
  274. }
  275. /**
  276. * Create an instance of the "error log" log driver.
  277. *
  278. * @param array $config
  279. * @return \Psr\Log\LoggerInterface
  280. */
  281. protected function createErrorlogDriver(array $config)
  282. {
  283. return new Monolog($this->parseChannel($config), [
  284. $this->prepareHandler(new ErrorLogHandler(
  285. $config['type'] ?? ErrorLogHandler::OPERATING_SYSTEM, $this->level($config))
  286. ),
  287. ]);
  288. }
  289. /**
  290. * Create an instance of any handler available in Monolog.
  291. *
  292. * @param array $config
  293. * @return \Psr\Log\LoggerInterface
  294. *
  295. * @throws \InvalidArgumentException
  296. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  297. */
  298. protected function createMonologDriver(array $config)
  299. {
  300. if (! is_a($config['handler'], HandlerInterface::class, true)) {
  301. throw new InvalidArgumentException(
  302. $config['handler'].' must be an instance of '.HandlerInterface::class
  303. );
  304. }
  305. $with = array_merge($config['with'] ?? [], $config['handler_with'] ?? []);
  306. return new Monolog($this->parseChannel($config), [$this->prepareHandler(
  307. $this->app->make($config['handler'], $with), $config
  308. )]);
  309. }
  310. /**
  311. * Prepare the handlers for usage by Monolog.
  312. *
  313. * @param array $handlers
  314. * @return array
  315. */
  316. protected function prepareHandlers(array $handlers)
  317. {
  318. foreach ($handlers as $key => $handler) {
  319. $handlers[$key] = $this->prepareHandler($handler);
  320. }
  321. return $handlers;
  322. }
  323. /**
  324. * Prepare the handler for usage by Monolog.
  325. *
  326. * @param \Monolog\Handler\HandlerInterface $handler
  327. * @param array $config
  328. * @return \Monolog\Handler\HandlerInterface
  329. */
  330. protected function prepareHandler(HandlerInterface $handler, array $config = [])
  331. {
  332. if (! isset($config['formatter'])) {
  333. $handler->setFormatter($this->formatter());
  334. } elseif ($config['formatter'] !== 'default') {
  335. $handler->setFormatter($this->app->make($config['formatter'], $config['formatter_with'] ?? []));
  336. }
  337. return $handler;
  338. }
  339. /**
  340. * Get a Monolog formatter instance.
  341. *
  342. * @return \Monolog\Formatter\FormatterInterface
  343. */
  344. protected function formatter()
  345. {
  346. return tap(new LineFormatter(null, null, true, true), function ($formatter) {
  347. $formatter->includeStacktraces();
  348. });
  349. }
  350. /**
  351. * Extract the log channel from the given configuration.
  352. *
  353. * @param array $config
  354. * @return string
  355. */
  356. protected function parseChannel(array $config)
  357. {
  358. if (! isset($config['name'])) {
  359. return $this->app->bound('env') ? $this->app->environment() : 'production';
  360. }
  361. return $config['name'];
  362. }
  363. /**
  364. * Parse the string level into a Monolog constant.
  365. *
  366. * @param array $config
  367. * @return int
  368. *
  369. * @throws \InvalidArgumentException
  370. */
  371. protected function level(array $config)
  372. {
  373. $level = $config['level'] ?? 'debug';
  374. if (isset($this->levels[$level])) {
  375. return $this->levels[$level];
  376. }
  377. throw new InvalidArgumentException('Invalid log level.');
  378. }
  379. /**
  380. * Get the log connection configuration.
  381. *
  382. * @param string $name
  383. * @return array
  384. */
  385. protected function configurationFor($name)
  386. {
  387. return $this->app['config']["logging.channels.{$name}"];
  388. }
  389. /**
  390. * Get the default log driver name.
  391. *
  392. * @return string
  393. */
  394. public function getDefaultDriver()
  395. {
  396. return $this->app['config']['logging.default'];
  397. }
  398. /**
  399. * Set the default log driver name.
  400. *
  401. * @param string $name
  402. * @return void
  403. */
  404. public function setDefaultDriver($name)
  405. {
  406. $this->app['config']['logging.default'] = $name;
  407. }
  408. /**
  409. * Register a custom driver creator Closure.
  410. *
  411. * @param string $driver
  412. * @param \Closure $callback
  413. * @return $this
  414. */
  415. public function extend($driver, Closure $callback)
  416. {
  417. $this->customCreators[$driver] = $callback->bindTo($this, $this);
  418. return $this;
  419. }
  420. /**
  421. * System is unusable.
  422. *
  423. * @param string $message
  424. * @param array $context
  425. *
  426. * @return void
  427. */
  428. public function emergency($message, array $context = [])
  429. {
  430. return $this->driver()->emergency($message, $context);
  431. }
  432. /**
  433. * Action must be taken immediately.
  434. *
  435. * Example: Entire website down, database unavailable, etc. This should
  436. * trigger the SMS alerts and wake you up.
  437. *
  438. * @param string $message
  439. * @param array $context
  440. *
  441. * @return void
  442. */
  443. public function alert($message, array $context = [])
  444. {
  445. return $this->driver()->alert($message, $context);
  446. }
  447. /**
  448. * Critical conditions.
  449. *
  450. * Example: Application component unavailable, unexpected exception.
  451. *
  452. * @param string $message
  453. * @param array $context
  454. *
  455. * @return void
  456. */
  457. public function critical($message, array $context = [])
  458. {
  459. return $this->driver()->critical($message, $context);
  460. }
  461. /**
  462. * Runtime errors that do not require immediate action but should typically
  463. * be logged and monitored.
  464. *
  465. * @param string $message
  466. * @param array $context
  467. *
  468. * @return void
  469. */
  470. public function error($message, array $context = [])
  471. {
  472. return $this->driver()->error($message, $context);
  473. }
  474. /**
  475. * Exceptional occurrences that are not errors.
  476. *
  477. * Example: Use of deprecated APIs, poor use of an API, undesirable things
  478. * that are not necessarily wrong.
  479. *
  480. * @param string $message
  481. * @param array $context
  482. *
  483. * @return void
  484. */
  485. public function warning($message, array $context = [])
  486. {
  487. return $this->driver()->warning($message, $context);
  488. }
  489. /**
  490. * Normal but significant events.
  491. *
  492. * @param string $message
  493. * @param array $context
  494. *
  495. * @return void
  496. */
  497. public function notice($message, array $context = [])
  498. {
  499. return $this->driver()->notice($message, $context);
  500. }
  501. /**
  502. * Interesting events.
  503. *
  504. * Example: User logs in, SQL logs.
  505. *
  506. * @param string $message
  507. * @param array $context
  508. *
  509. * @return void
  510. */
  511. public function info($message, array $context = [])
  512. {
  513. return $this->driver()->info($message, $context);
  514. }
  515. /**
  516. * Detailed debug information.
  517. *
  518. * @param string $message
  519. * @param array $context
  520. *
  521. * @return void
  522. */
  523. public function debug($message, array $context = [])
  524. {
  525. return $this->driver()->debug($message, $context);
  526. }
  527. /**
  528. * Logs with an arbitrary level.
  529. *
  530. * @param mixed $level
  531. * @param string $message
  532. * @param array $context
  533. *
  534. * @return void
  535. */
  536. public function log($level, $message, array $context = [])
  537. {
  538. return $this->driver()->log($level, $message, $context);
  539. }
  540. /**
  541. * Dynamically call the default driver instance.
  542. *
  543. * @param string $method
  544. * @param array $parameters
  545. * @return mixed
  546. */
  547. public function __call($method, $parameters)
  548. {
  549. return $this->driver()->$method(...$parameters);
  550. }
  551. }