Log.php 13 KB

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