1
0

Log.php 13 KB

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