Log.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Olivier Paroz <github@oparoz.com>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC;
  32. use InterfaSys\LogNormalizer\Normalizer;
  33. use \OCP\ILogger;
  34. use OCP\Security\StringUtils;
  35. use OCP\Util;
  36. /**
  37. * logging utilities
  38. *
  39. * This is a stand in, this should be replaced by a Psr\Log\LoggerInterface
  40. * compatible logger. See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
  41. * for the full interface specification.
  42. *
  43. * MonoLog is an example implementing this interface.
  44. */
  45. class Log implements ILogger {
  46. /** @var string */
  47. private $logger;
  48. /** @var SystemConfig */
  49. private $config;
  50. /** @var boolean|null cache the result of the log condition check for the request */
  51. private $logConditionSatisfied = null;
  52. /** @var Normalizer */
  53. private $normalizer;
  54. protected $methodsWithSensitiveParameters = [
  55. // Session/User
  56. 'login',
  57. 'checkPassword',
  58. 'loginWithPassword',
  59. 'updatePrivateKeyPassword',
  60. 'validateUserPass',
  61. // TokenProvider
  62. 'getToken',
  63. 'isTokenPassword',
  64. 'getPassword',
  65. 'decryptPassword',
  66. 'logClientIn',
  67. 'generateToken',
  68. 'validateToken',
  69. // TwoFactorAuth
  70. 'solveChallenge',
  71. 'verifyChallenge',
  72. //ICrypto
  73. 'calculateHMAC',
  74. 'encrypt',
  75. 'decrypt',
  76. //LoginController
  77. 'tryLogin',
  78. 'confirmPassword',
  79. ];
  80. /**
  81. * @param string $logger The logger that should be used
  82. * @param SystemConfig $config the system config object
  83. * @param null $normalizer
  84. */
  85. public function __construct($logger=null, SystemConfig $config=null, $normalizer = null) {
  86. // FIXME: Add this for backwards compatibility, should be fixed at some point probably
  87. if($config === null) {
  88. $config = \OC::$server->getSystemConfig();
  89. }
  90. $this->config = $config;
  91. // FIXME: Add this for backwards compatibility, should be fixed at some point probably
  92. if($logger === null) {
  93. $logType = $this->config->getValue('log_type', 'file');
  94. $this->logger = static::getLogClass($logType);
  95. call_user_func(array($this->logger, 'init'));
  96. } else {
  97. $this->logger = $logger;
  98. }
  99. if ($normalizer === null) {
  100. $this->normalizer = new Normalizer();
  101. } else {
  102. $this->normalizer = $normalizer;
  103. }
  104. }
  105. /**
  106. * System is unusable.
  107. *
  108. * @param string $message
  109. * @param array $context
  110. * @return void
  111. */
  112. public function emergency($message, array $context = array()) {
  113. $this->log(Util::FATAL, $message, $context);
  114. }
  115. /**
  116. * Action must be taken immediately.
  117. *
  118. * Example: Entire website down, database unavailable, etc. This should
  119. * trigger the SMS alerts and wake you up.
  120. *
  121. * @param string $message
  122. * @param array $context
  123. * @return void
  124. */
  125. public function alert($message, array $context = array()) {
  126. $this->log(Util::ERROR, $message, $context);
  127. }
  128. /**
  129. * Critical conditions.
  130. *
  131. * Example: Application component unavailable, unexpected exception.
  132. *
  133. * @param string $message
  134. * @param array $context
  135. * @return void
  136. */
  137. public function critical($message, array $context = array()) {
  138. $this->log(Util::ERROR, $message, $context);
  139. }
  140. /**
  141. * Runtime errors that do not require immediate action but should typically
  142. * be logged and monitored.
  143. *
  144. * @param string $message
  145. * @param array $context
  146. * @return void
  147. */
  148. public function error($message, array $context = array()) {
  149. $this->log(Util::ERROR, $message, $context);
  150. }
  151. /**
  152. * Exceptional occurrences that are not errors.
  153. *
  154. * Example: Use of deprecated APIs, poor use of an API, undesirable things
  155. * that are not necessarily wrong.
  156. *
  157. * @param string $message
  158. * @param array $context
  159. * @return void
  160. */
  161. public function warning($message, array $context = array()) {
  162. $this->log(Util::WARN, $message, $context);
  163. }
  164. /**
  165. * Normal but significant events.
  166. *
  167. * @param string $message
  168. * @param array $context
  169. * @return void
  170. */
  171. public function notice($message, array $context = array()) {
  172. $this->log(Util::INFO, $message, $context);
  173. }
  174. /**
  175. * Interesting events.
  176. *
  177. * Example: User logs in, SQL logs.
  178. *
  179. * @param string $message
  180. * @param array $context
  181. * @return void
  182. */
  183. public function info($message, array $context = array()) {
  184. $this->log(Util::INFO, $message, $context);
  185. }
  186. /**
  187. * Detailed debug information.
  188. *
  189. * @param string $message
  190. * @param array $context
  191. * @return void
  192. */
  193. public function debug($message, array $context = array()) {
  194. $this->log(Util::DEBUG, $message, $context);
  195. }
  196. /**
  197. * Logs with an arbitrary level.
  198. *
  199. * @param mixed $level
  200. * @param string $message
  201. * @param array $context
  202. * @return void
  203. */
  204. public function log($level, $message, array $context = array()) {
  205. $minLevel = min($this->config->getValue('loglevel', Util::WARN), Util::FATAL);
  206. $logCondition = $this->config->getValue('log.condition', []);
  207. array_walk($context, [$this->normalizer, 'format']);
  208. if (isset($context['app'])) {
  209. $app = $context['app'];
  210. /**
  211. * check log condition based on the context of each log message
  212. * once this is met -> change the required log level to debug
  213. */
  214. if(!empty($logCondition)
  215. && isset($logCondition['apps'])
  216. && in_array($app, $logCondition['apps'], true)) {
  217. $minLevel = Util::DEBUG;
  218. }
  219. } else {
  220. $app = 'no app in context';
  221. }
  222. // interpolate $message as defined in PSR-3
  223. $replace = array();
  224. foreach ($context as $key => $val) {
  225. $replace['{' . $key . '}'] = $val;
  226. }
  227. // interpolate replacement values into the message and return
  228. $message = strtr($message, $replace);
  229. /**
  230. * check for a special log condition - this enables an increased log on
  231. * a per request/user base
  232. */
  233. if($this->logConditionSatisfied === null) {
  234. // default to false to just process this once per request
  235. $this->logConditionSatisfied = false;
  236. if(!empty($logCondition)) {
  237. // check for secret token in the request
  238. if(isset($logCondition['shared_secret'])) {
  239. $request = \OC::$server->getRequest();
  240. // if token is found in the request change set the log condition to satisfied
  241. if($request && hash_equals($logCondition['shared_secret'], $request->getParam('log_secret', ''))) {
  242. $this->logConditionSatisfied = true;
  243. }
  244. }
  245. // check for user
  246. if(isset($logCondition['users'])) {
  247. $user = \OC::$server->getUserSession()->getUser();
  248. // if the user matches set the log condition to satisfied
  249. if($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
  250. $this->logConditionSatisfied = true;
  251. }
  252. }
  253. }
  254. }
  255. // if log condition is satisfied change the required log level to DEBUG
  256. if($this->logConditionSatisfied) {
  257. $minLevel = Util::DEBUG;
  258. }
  259. if ($level >= $minLevel) {
  260. $logger = $this->logger;
  261. call_user_func(array($logger, 'write'), $app, $message, $level);
  262. }
  263. }
  264. /**
  265. * Logs an exception very detailed
  266. *
  267. * @param \Exception | \Throwable $exception
  268. * @param array $context
  269. * @return void
  270. * @since 8.2.0
  271. */
  272. public function logException($exception, array $context = array()) {
  273. $exception = array(
  274. 'Exception' => get_class($exception),
  275. 'Message' => $exception->getMessage(),
  276. 'Code' => $exception->getCode(),
  277. 'Trace' => $exception->getTraceAsString(),
  278. 'File' => $exception->getFile(),
  279. 'Line' => $exception->getLine(),
  280. );
  281. $exception['Trace'] = preg_replace('!(' . implode('|', $this->methodsWithSensitiveParameters) . ')\(.*\)!', '$1(*** sensitive parameters replaced ***)', $exception['Trace']);
  282. $msg = isset($context['message']) ? $context['message'] : 'Exception';
  283. $msg .= ': ' . json_encode($exception);
  284. $this->error($msg, $context);
  285. }
  286. /**
  287. * @param string $logType
  288. * @return string
  289. * @internal
  290. */
  291. public static function getLogClass($logType) {
  292. switch (strtolower($logType)) {
  293. case 'errorlog':
  294. return \OC\Log\Errorlog::class;
  295. case 'syslog':
  296. return \OC\Log\Syslog::class;
  297. case 'file':
  298. return \OC\Log\File::class;
  299. // Backwards compatibility for old and fallback for unknown log types
  300. case 'owncloud':
  301. case 'nextcloud':
  302. default:
  303. return \OC\Log\File::class;
  304. }
  305. }
  306. }