1
0

Log.php 12 KB

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