1
0

Log.php 12 KB

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