Log.php 14 KB

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