You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Log.php 13KB

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