Log.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Olivier Paroz <github@oparoz.com>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Citharel <nextcloud@tcit.fr>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC;
  36. use Exception;
  37. use Nextcloud\LogNormalizer\Normalizer;
  38. use OC\AppFramework\Bootstrap\Coordinator;
  39. use OC\Log\ExceptionSerializer;
  40. use OCP\EventDispatcher\IEventDispatcher;
  41. use OCP\ILogger;
  42. use OCP\IUserSession;
  43. use OCP\Log\BeforeMessageLoggedEvent;
  44. use OCP\Log\IDataLogger;
  45. use OCP\Log\IFileBased;
  46. use OCP\Log\IWriter;
  47. use OCP\Support\CrashReport\IRegistry;
  48. use Throwable;
  49. use function array_merge;
  50. use function strtr;
  51. /**
  52. * logging utilities
  53. *
  54. * This is a stand in, this should be replaced by a Psr\Log\LoggerInterface
  55. * compatible logger. See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
  56. * for the full interface specification.
  57. *
  58. * MonoLog is an example implementing this interface.
  59. */
  60. class Log implements ILogger, IDataLogger {
  61. private ?SystemConfig $config;
  62. private ?bool $logConditionSatisfied = null;
  63. private ?Normalizer $normalizer;
  64. private ?IEventDispatcher $eventDispatcher;
  65. /**
  66. * @param IWriter $logger The logger that should be used
  67. * @param SystemConfig|null $config the system config object
  68. * @param Normalizer|null $normalizer
  69. * @param IRegistry|null $crashReporters
  70. */
  71. public function __construct(
  72. private IWriter $logger,
  73. SystemConfig $config = null,
  74. Normalizer $normalizer = null,
  75. private ?IRegistry $crashReporters = null
  76. ) {
  77. // FIXME: Add this for backwards compatibility, should be fixed at some point probably
  78. if ($config === null) {
  79. $config = \OC::$server->getSystemConfig();
  80. }
  81. $this->config = $config;
  82. if ($normalizer === null) {
  83. $this->normalizer = new Normalizer();
  84. } else {
  85. $this->normalizer = $normalizer;
  86. }
  87. $this->eventDispatcher = null;
  88. }
  89. public function setEventDispatcher(IEventDispatcher $eventDispatcher) {
  90. $this->eventDispatcher = $eventDispatcher;
  91. }
  92. /**
  93. * System is unusable.
  94. *
  95. * @param string $message
  96. * @param array $context
  97. * @return void
  98. */
  99. public function emergency(string $message, array $context = []) {
  100. $this->log(ILogger::FATAL, $message, $context);
  101. }
  102. /**
  103. * Action must be taken immediately.
  104. *
  105. * Example: Entire website down, database unavailable, etc. This should
  106. * trigger the SMS alerts and wake you up.
  107. *
  108. * @param string $message
  109. * @param array $context
  110. * @return void
  111. */
  112. public function alert(string $message, array $context = []) {
  113. $this->log(ILogger::ERROR, $message, $context);
  114. }
  115. /**
  116. * Critical conditions.
  117. *
  118. * Example: Application component unavailable, unexpected exception.
  119. *
  120. * @param string $message
  121. * @param array $context
  122. * @return void
  123. */
  124. public function critical(string $message, array $context = []) {
  125. $this->log(ILogger::ERROR, $message, $context);
  126. }
  127. /**
  128. * Runtime errors that do not require immediate action but should typically
  129. * be logged and monitored.
  130. *
  131. * @param string $message
  132. * @param array $context
  133. * @return void
  134. */
  135. public function error(string $message, array $context = []) {
  136. $this->log(ILogger::ERROR, $message, $context);
  137. }
  138. /**
  139. * Exceptional occurrences that are not errors.
  140. *
  141. * Example: Use of deprecated APIs, poor use of an API, undesirable things
  142. * that are not necessarily wrong.
  143. *
  144. * @param string $message
  145. * @param array $context
  146. * @return void
  147. */
  148. public function warning(string $message, array $context = []) {
  149. $this->log(ILogger::WARN, $message, $context);
  150. }
  151. /**
  152. * Normal but significant events.
  153. *
  154. * @param string $message
  155. * @param array $context
  156. * @return void
  157. */
  158. public function notice(string $message, array $context = []) {
  159. $this->log(ILogger::INFO, $message, $context);
  160. }
  161. /**
  162. * Interesting events.
  163. *
  164. * Example: User logs in, SQL logs.
  165. *
  166. * @param string $message
  167. * @param array $context
  168. * @return void
  169. */
  170. public function info(string $message, array $context = []) {
  171. $this->log(ILogger::INFO, $message, $context);
  172. }
  173. /**
  174. * Detailed debug information.
  175. *
  176. * @param string $message
  177. * @param array $context
  178. * @return void
  179. */
  180. public function debug(string $message, array $context = []) {
  181. $this->log(ILogger::DEBUG, $message, $context);
  182. }
  183. /**
  184. * Logs with an arbitrary level.
  185. *
  186. * @param int $level
  187. * @param string $message
  188. * @param array $context
  189. * @return void
  190. */
  191. public function log(int $level, string $message, array $context = []) {
  192. $minLevel = $this->getLogLevel($context);
  193. if ($level < $minLevel
  194. && (($this->crashReporters?->hasReporters() ?? false) === false)
  195. && (($this->eventDispatcher?->hasListeners(BeforeMessageLoggedEvent::class) ?? false) === false)) {
  196. return; // no crash reporter, no listeners, we can stop for lower log level
  197. }
  198. array_walk($context, [$this->normalizer, 'format']);
  199. $app = $context['app'] ?? 'no app in context';
  200. $entry = $this->interpolateMessage($context, $message);
  201. $this->eventDispatcher?->dispatchTyped(new BeforeMessageLoggedEvent($app, $level, $entry));
  202. $hasBacktrace = isset($entry['exception']);
  203. $logBacktrace = $this->config->getValue('log.backtrace', false);
  204. if (!$hasBacktrace && $logBacktrace) {
  205. $entry['backtrace'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  206. }
  207. try {
  208. if ($level >= $minLevel) {
  209. $this->writeLog($app, $entry, $level);
  210. if ($this->crashReporters !== null) {
  211. $messageContext = array_merge(
  212. $context,
  213. [
  214. 'level' => $level
  215. ]
  216. );
  217. $this->crashReporters->delegateMessage($entry['message'], $messageContext);
  218. }
  219. } else {
  220. $this->crashReporters?->delegateBreadcrumb($entry['message'], 'log', $context);
  221. }
  222. } catch (Throwable $e) {
  223. // make sure we dont hard crash if logging fails
  224. }
  225. }
  226. public function getLogLevel($context) {
  227. $logCondition = $this->config->getValue('log.condition', []);
  228. /**
  229. * check for a special log condition - this enables an increased log on
  230. * a per request/user base
  231. */
  232. if ($this->logConditionSatisfied === null) {
  233. // default to false to just process this once per request
  234. $this->logConditionSatisfied = false;
  235. if (!empty($logCondition)) {
  236. // check for secret token in the request
  237. if (isset($logCondition['shared_secret'])) {
  238. $request = \OC::$server->getRequest();
  239. if ($request->getMethod() === 'PUT' &&
  240. !str_contains($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') &&
  241. !str_contains($request->getHeader('Content-Type'), 'application/json')) {
  242. $logSecretRequest = '';
  243. } else {
  244. $logSecretRequest = $request->getParam('log_secret', '');
  245. }
  246. // if token is found in the request change set the log condition to satisfied
  247. if ($request && hash_equals($logCondition['shared_secret'], $logSecretRequest)) {
  248. $this->logConditionSatisfied = true;
  249. }
  250. }
  251. // check for user
  252. if (isset($logCondition['users'])) {
  253. $user = \OCP\Server::get(IUserSession::class)->getUser();
  254. if ($user === null) {
  255. // User is not known for this request yet
  256. $this->logConditionSatisfied = null;
  257. } elseif (in_array($user->getUID(), $logCondition['users'], true)) {
  258. // if the user matches set the log condition to satisfied
  259. $this->logConditionSatisfied = true;
  260. }
  261. }
  262. }
  263. }
  264. // if log condition is satisfied change the required log level to DEBUG
  265. if ($this->logConditionSatisfied) {
  266. return ILogger::DEBUG;
  267. }
  268. if (isset($context['app'])) {
  269. $app = $context['app'];
  270. /**
  271. * check log condition based on the context of each log message
  272. * once this is met -> change the required log level to debug
  273. */
  274. if (!empty($logCondition)
  275. && isset($logCondition['apps'])
  276. && in_array($app, $logCondition['apps'], true)) {
  277. return ILogger::DEBUG;
  278. }
  279. }
  280. return min($this->config->getValue('loglevel', ILogger::WARN), ILogger::FATAL);
  281. }
  282. /**
  283. * Logs an exception very detailed
  284. *
  285. * @param Exception|Throwable $exception
  286. * @param array $context
  287. * @return void
  288. * @since 8.2.0
  289. */
  290. public function logException(Throwable $exception, array $context = []) {
  291. $app = $context['app'] ?? 'no app in context';
  292. $level = $context['level'] ?? ILogger::ERROR;
  293. $minLevel = $this->getLogLevel($context);
  294. if ($level < $minLevel
  295. && (($this->crashReporters?->hasReporters() ?? false) === false)
  296. && (($this->eventDispatcher?->hasListeners(BeforeMessageLoggedEvent::class) ?? false) === false)) {
  297. return; // no crash reporter, no listeners, we can stop for lower log level
  298. }
  299. // if an error is raised before the autoloader is properly setup, we can't serialize exceptions
  300. try {
  301. $serializer = $this->getSerializer();
  302. } catch (Throwable $e) {
  303. $this->error("Failed to load ExceptionSerializer serializer while trying to log " . $exception->getMessage());
  304. return;
  305. }
  306. $data = $context;
  307. unset($data['app']);
  308. unset($data['level']);
  309. $data = array_merge($serializer->serializeException($exception), $data);
  310. $data = $this->interpolateMessage($data, isset($context['message']) && $context['message'] !== '' ? $context['message'] : ('Exception thrown: ' . get_class($exception)), 'CustomMessage');
  311. array_walk($context, [$this->normalizer, 'format']);
  312. $this->eventDispatcher?->dispatchTyped(new BeforeMessageLoggedEvent($app, $level, $data));
  313. try {
  314. if ($level >= $minLevel) {
  315. if (!$this->logger instanceof IFileBased) {
  316. $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES);
  317. }
  318. $this->writeLog($app, $data, $level);
  319. }
  320. $context['level'] = $level;
  321. if (!is_null($this->crashReporters)) {
  322. $this->crashReporters->delegateReport($exception, $context);
  323. }
  324. } catch (Throwable $e) {
  325. // make sure we dont hard crash if logging fails
  326. }
  327. }
  328. public function logData(string $message, array $data, array $context = []): void {
  329. $app = $context['app'] ?? 'no app in context';
  330. $level = $context['level'] ?? ILogger::ERROR;
  331. $minLevel = $this->getLogLevel($context);
  332. array_walk($context, [$this->normalizer, 'format']);
  333. try {
  334. if ($level >= $minLevel) {
  335. $data['message'] = $message;
  336. if (!$this->logger instanceof IFileBased) {
  337. $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES);
  338. }
  339. $this->writeLog($app, $data, $level);
  340. }
  341. $context['level'] = $level;
  342. } catch (Throwable $e) {
  343. // make sure we dont hard crash if logging fails
  344. error_log('Error when trying to log exception: ' . $e->getMessage() . ' ' . $e->getTraceAsString());
  345. }
  346. }
  347. /**
  348. * @param string $app
  349. * @param string|array $entry
  350. * @param int $level
  351. */
  352. protected function writeLog(string $app, $entry, int $level) {
  353. $this->logger->write($app, $entry, $level);
  354. }
  355. public function getLogPath():string {
  356. if ($this->logger instanceof IFileBased) {
  357. return $this->logger->getLogFilePath();
  358. }
  359. throw new \RuntimeException('Log implementation has no path');
  360. }
  361. /**
  362. * Interpolate $message as defined in PSR-3
  363. *
  364. * Returns an array containing the context without the interpolated
  365. * parameters placeholders and the message as the 'message' - or
  366. * user-defined - key.
  367. */
  368. private function interpolateMessage(array $context, string $message, string $messageKey = 'message'): array {
  369. $replace = [];
  370. $usedContextKeys = [];
  371. foreach ($context as $key => $val) {
  372. $fullKey = '{' . $key . '}';
  373. $replace[$fullKey] = $val;
  374. if (str_contains($message, $fullKey)) {
  375. $usedContextKeys[$key] = true;
  376. }
  377. }
  378. return array_merge(array_diff_key($context, $usedContextKeys), [$messageKey => strtr($message, $replace)]);
  379. }
  380. /**
  381. * @throws Throwable
  382. */
  383. protected function getSerializer(): ExceptionSerializer {
  384. $serializer = new ExceptionSerializer($this->config);
  385. try {
  386. /** @var Coordinator $coordinator */
  387. $coordinator = \OCP\Server::get(Coordinator::class);
  388. foreach ($coordinator->getRegistrationContext()->getSensitiveMethods() as $registration) {
  389. $serializer->enlistSensitiveMethods($registration->getName(), $registration->getValue());
  390. }
  391. // For not every app might be initialized at this time, we cannot assume that the return value
  392. // of getSensitiveMethods() is complete. Running delegates in Coordinator::registerApps() is
  393. // not possible due to dependencies on the one hand. On the other it would work only with
  394. // adding public methods to the PsrLoggerAdapter and this class.
  395. // Thus, serializer cannot be a property.
  396. } catch (Throwable $t) {
  397. // ignore app-defined sensitive methods in this case - they weren't loaded anyway
  398. }
  399. return $serializer;
  400. }
  401. }