Log.php 13 KB

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