1
0

Log.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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\ILogger;
  40. use OCP\IUserSession;
  41. use OCP\Log\BeforeMessageLoggedEvent;
  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. $hasBacktrace = isset($entry['exception']);
  204. $logBacktrace = $this->config->getValue('log.backtrace', false);
  205. if (!$hasBacktrace && $logBacktrace) {
  206. $entry['backtrace'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  207. }
  208. try {
  209. if ($level >= $minLevel) {
  210. $this->writeLog($app, $entry, $level);
  211. if ($this->crashReporters !== null) {
  212. $messageContext = array_merge(
  213. $context,
  214. [
  215. 'level' => $level
  216. ]
  217. );
  218. $this->crashReporters->delegateMessage($entry['message'], $messageContext);
  219. }
  220. } else {
  221. if ($this->crashReporters !== null) {
  222. $this->crashReporters->delegateBreadcrumb($entry['message'], 'log', $context);
  223. }
  224. }
  225. } catch (Throwable $e) {
  226. // make sure we dont hard crash if logging fails
  227. }
  228. }
  229. public function getLogLevel($context) {
  230. $logCondition = $this->config->getValue('log.condition', []);
  231. /**
  232. * check for a special log condition - this enables an increased log on
  233. * a per request/user base
  234. */
  235. if ($this->logConditionSatisfied === null) {
  236. // default to false to just process this once per request
  237. $this->logConditionSatisfied = false;
  238. if (!empty($logCondition)) {
  239. // check for secret token in the request
  240. if (isset($logCondition['shared_secret'])) {
  241. $request = \OC::$server->getRequest();
  242. if ($request->getMethod() === 'PUT' &&
  243. !str_contains($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') &&
  244. !str_contains($request->getHeader('Content-Type'), 'application/json')) {
  245. $logSecretRequest = '';
  246. } else {
  247. $logSecretRequest = $request->getParam('log_secret', '');
  248. }
  249. // if token is found in the request change set the log condition to satisfied
  250. if ($request && hash_equals($logCondition['shared_secret'], $logSecretRequest)) {
  251. $this->logConditionSatisfied = true;
  252. }
  253. }
  254. // check for user
  255. if (isset($logCondition['users'])) {
  256. $user = \OCP\Server::get(IUserSession::class)->getUser();
  257. if ($user === null) {
  258. // User is not known for this request yet
  259. $this->logConditionSatisfied = null;
  260. } elseif (in_array($user->getUID(), $logCondition['users'], true)) {
  261. // if the user matches set the log condition to satisfied
  262. $this->logConditionSatisfied = true;
  263. }
  264. }
  265. }
  266. }
  267. // if log condition is satisfied change the required log level to DEBUG
  268. if ($this->logConditionSatisfied) {
  269. return ILogger::DEBUG;
  270. }
  271. if (isset($context['app'])) {
  272. $app = $context['app'];
  273. /**
  274. * check log condition based on the context of each log message
  275. * once this is met -> change the required log level to debug
  276. */
  277. if (!empty($logCondition)
  278. && isset($logCondition['apps'])
  279. && in_array($app, $logCondition['apps'], true)) {
  280. return ILogger::DEBUG;
  281. }
  282. }
  283. return min($this->config->getValue('loglevel', ILogger::WARN), ILogger::FATAL);
  284. }
  285. /**
  286. * Logs an exception very detailed
  287. *
  288. * @param Exception|Throwable $exception
  289. * @param array $context
  290. * @return void
  291. * @since 8.2.0
  292. */
  293. public function logException(Throwable $exception, array $context = []) {
  294. $app = $context['app'] ?? 'no app in context';
  295. $level = $context['level'] ?? ILogger::ERROR;
  296. $minLevel = $this->getLogLevel($context);
  297. if ($level < $minLevel && ($this->crashReporters === null || !$this->crashReporters->hasReporters())) {
  298. return;
  299. }
  300. // if an error is raised before the autoloader is properly setup, we can't serialize exceptions
  301. try {
  302. $serializer = $this->getSerializer();
  303. } catch (Throwable $e) {
  304. $this->error("Failed to load ExceptionSerializer serializer while trying to log " . $exception->getMessage());
  305. return;
  306. }
  307. $data = $context;
  308. unset($data['app']);
  309. unset($data['level']);
  310. $data = array_merge($serializer->serializeException($exception), $data);
  311. $data = $this->interpolateMessage($data, $context['message'] ?? '--', 'CustomMessage');
  312. array_walk($context, [$this->normalizer, 'format']);
  313. if ($this->eventDispatcher) {
  314. $this->eventDispatcher->dispatchTyped(new BeforeMessageLoggedEvent($app, $level, $data));
  315. }
  316. try {
  317. if ($level >= $minLevel) {
  318. if (!$this->logger instanceof IFileBased) {
  319. $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES);
  320. }
  321. $this->writeLog($app, $data, $level);
  322. }
  323. $context['level'] = $level;
  324. if (!is_null($this->crashReporters)) {
  325. $this->crashReporters->delegateReport($exception, $context);
  326. }
  327. } catch (Throwable $e) {
  328. // make sure we dont hard crash if logging fails
  329. }
  330. }
  331. public function logData(string $message, array $data, array $context = []): void {
  332. $app = $context['app'] ?? 'no app in context';
  333. $level = $context['level'] ?? ILogger::ERROR;
  334. $minLevel = $this->getLogLevel($context);
  335. array_walk($context, [$this->normalizer, 'format']);
  336. try {
  337. if ($level >= $minLevel) {
  338. $data['message'] = $message;
  339. if (!$this->logger instanceof IFileBased) {
  340. $data = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES);
  341. }
  342. $this->writeLog($app, $data, $level);
  343. }
  344. $context['level'] = $level;
  345. } catch (Throwable $e) {
  346. // make sure we dont hard crash if logging fails
  347. error_log('Error when trying to log exception: ' . $e->getMessage() . ' ' . $e->getTraceAsString());
  348. }
  349. }
  350. /**
  351. * @param string $app
  352. * @param string|array $entry
  353. * @param int $level
  354. */
  355. protected function writeLog(string $app, $entry, int $level) {
  356. $this->logger->write($app, $entry, $level);
  357. }
  358. public function getLogPath():string {
  359. if ($this->logger instanceof IFileBased) {
  360. return $this->logger->getLogFilePath();
  361. }
  362. throw new \RuntimeException('Log implementation has no path');
  363. }
  364. /**
  365. * Interpolate $message as defined in PSR-3
  366. *
  367. * Returns an array containing the context without the interpolated
  368. * parameters placeholders and the message as the 'message' - or
  369. * user-defined - key.
  370. */
  371. private function interpolateMessage(array $context, string $message, string $messageKey = 'message'): array {
  372. $replace = [];
  373. $usedContextKeys = [];
  374. foreach ($context as $key => $val) {
  375. $fullKey = '{' . $key . '}';
  376. $replace[$fullKey] = $val;
  377. if (str_contains($message, $fullKey)) {
  378. $usedContextKeys[$key] = true;
  379. }
  380. }
  381. return array_merge(array_diff_key($context, $usedContextKeys), [$messageKey => strtr($message, $replace)]);
  382. }
  383. /**
  384. * @throws Throwable
  385. */
  386. protected function getSerializer(): ExceptionSerializer {
  387. $serializer = new ExceptionSerializer($this->config);
  388. try {
  389. /** @var Coordinator $coordinator */
  390. $coordinator = \OCP\Server::get(Coordinator::class);
  391. foreach ($coordinator->getRegistrationContext()->getSensitiveMethods() as $registration) {
  392. $serializer->enlistSensitiveMethods($registration->getName(), $registration->getValue());
  393. }
  394. // For not every app might be initialized at this time, we cannot assume that the return value
  395. // of getSensitiveMethods() is complete. Running delegates in Coordinator::registerApps() is
  396. // not possible due to dependencies on the one hand. On the other it would work only with
  397. // adding public methods to the PsrLoggerAdapter and this class.
  398. // Thus, serializer cannot be a property.
  399. } catch (Throwable $t) {
  400. // ignore app-defined sensitive methods in this case - they weren't loaded anyway
  401. }
  402. return $serializer;
  403. }
  404. }