1
0

Log.php 14 KB

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