diff options
Diffstat (limited to 'lib/private/Log')
-rw-r--r-- | lib/private/Log/ErrorHandler.php | 56 | ||||
-rw-r--r-- | lib/private/Log/Errorlog.php | 42 | ||||
-rw-r--r-- | lib/private/Log/ExceptionSerializer.php | 97 | ||||
-rw-r--r-- | lib/private/Log/File.php | 73 | ||||
-rw-r--r-- | lib/private/Log/LogDetails.php | 43 | ||||
-rw-r--r-- | lib/private/Log/LogFactory.php | 88 | ||||
-rw-r--r-- | lib/private/Log/PsrLoggerAdapter.php | 225 | ||||
-rw-r--r-- | lib/private/Log/Rotate.php | 49 | ||||
-rw-r--r-- | lib/private/Log/Syslog.php | 45 | ||||
-rw-r--r-- | lib/private/Log/Systemdlog.php | 42 |
10 files changed, 244 insertions, 516 deletions
diff --git a/lib/private/Log/ErrorHandler.php b/lib/private/Log/ErrorHandler.php index c4b9631e75a..6597274a868 100644 --- a/lib/private/Log/ErrorHandler.php +++ b/lib/private/Log/ErrorHandler.php @@ -1,32 +1,10 @@ <?php declare(strict_types=1); - /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bart Visscher <bartv@thisnet.nl> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Log; @@ -36,10 +14,9 @@ use Psr\Log\LoggerInterface; use Throwable; class ErrorHandler { - private LoggerInterface $logger; - - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + ) { } /** @@ -94,20 +71,11 @@ class ErrorHandler { } private static function errnoToLogLevel(int $errno): int { - switch ($errno) { - case E_USER_WARNING: - return ILogger::WARN; - - case E_DEPRECATED: - case E_USER_DEPRECATED: - return ILogger::DEBUG; - - case E_USER_NOTICE: - return ILogger::INFO; - - case E_USER_ERROR: - default: - return ILogger::ERROR; - } + return match ($errno) { + E_WARNING, E_USER_WARNING => ILogger::WARN, + E_DEPRECATED, E_USER_DEPRECATED => ILogger::DEBUG, + E_NOTICE, E_USER_NOTICE => ILogger::INFO, + default => ILogger::ERROR, + }; } } diff --git a/lib/private/Log/Errorlog.php b/lib/private/Log/Errorlog.php index 72d11aa098c..6188bb70fd5 100644 --- a/lib/private/Log/Errorlog.php +++ b/lib/private/Log/Errorlog.php @@ -1,53 +1,31 @@ <?php declare(strict_types=1); - /** - * The MIT License (MIT) - * - * Copyright (c) 2014 Christian Kampka <christian@kampka.net> - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-FileCopyrightText: 2014 Christian Kampka <christian@kampka.net> + * SPDX-License-Identifier: MIT */ - namespace OC\Log; use OC\SystemConfig; use OCP\Log\IWriter; class Errorlog extends LogDetails implements IWriter { - /** @var string */ - protected $tag; - - public function __construct(SystemConfig $config, string $tag = 'nextcloud') { + public function __construct( + SystemConfig $config, + protected string $tag = 'nextcloud', + ) { parent::__construct($config); - $this->tag = $tag; } /** * Write a message in the log * - * @param string $app * @param string|array $message - * @param int $level */ - public function write(string $app, $message, int $level) { - error_log('[' . $this->tag . ']['.$app.']['.$level.'] '.$this->logDetailsAsJSON($app, $message, $level)); + public function write(string $app, $message, int $level): void { + error_log('[' . $this->tag . '][' . $app . '][' . $level . '] ' . $this->logDetailsAsJSON($app, $message, $level)); } } diff --git a/lib/private/Log/ExceptionSerializer.php b/lib/private/Log/ExceptionSerializer.php index 5f806be0ae5..af7c9e48435 100644 --- a/lib/private/Log/ExceptionSerializer.php +++ b/lib/private/Log/ExceptionSerializer.php @@ -1,34 +1,13 @@ <?php + /** - * @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Log; use OC\Core\Controller\SetupController; +use OC\Http\Client\Client; use OC\Security\IdentityProof\Key; use OC\Setup; use OC\SystemConfig; @@ -36,8 +15,9 @@ use OCA\Encryption\Controller\RecoveryController; use OCA\Encryption\Controller\SettingsController; use OCA\Encryption\Crypto\Crypt; use OCA\Encryption\Crypto\Encryption; -use OCA\Encryption\Hooks\UserHooks; use OCA\Encryption\KeyManager; +use OCA\Encryption\Listeners\UserEventsListener; +use OCA\Encryption\Services\PassphraseService; use OCA\Encryption\Session; use OCP\HintException; @@ -55,6 +35,7 @@ class ExceptionSerializer { 'validateUserPass', 'loginWithToken', '{closure}', + '{closure:*', 'createSessionToken', // Provisioning @@ -100,13 +81,21 @@ class ExceptionSerializer { // Preview providers, don't log big data strings 'imagecreatefromstring', - ]; - /** @var SystemConfig */ - private $systemConfig; + // text: PublicSessionController, SessionController and ApiService + 'create', + 'close', + 'push', + 'sync', + 'updateSession', + 'mention', + 'loginSessionUser', + + ]; - public function __construct(SystemConfig $systemConfig) { - $this->systemConfig = $systemConfig; + public function __construct( + private SystemConfig $systemConfig, + ) { } protected array $methodsWithSensitiveParametersByClass = [ @@ -121,6 +110,22 @@ class ExceptionSerializer { Key::class => [ '__construct' ], + Client::class => [ + 'request', + 'delete', + 'deleteAsync', + 'get', + 'getAsync', + 'head', + 'headAsync', + 'options', + 'optionsAsync', + 'patch', + 'post', + 'postAsync', + 'put', + 'putAsync', + ], \Redis::class => [ 'auth' ], @@ -167,14 +172,16 @@ class ExceptionSerializer { \OCA\Encryption\Users\Setup::class => [ 'setupUser', ], - UserHooks::class => [ - 'login', - 'postCreateUser', - 'postDeleteUser', - 'prePasswordReset', - 'postPasswordReset', - 'preSetPassphrase', - 'setPassphrase', + UserEventsListener::class => [ + 'handle', + 'onUserCreated', + 'onUserLogin', + 'onBeforePasswordUpdated', + 'onPasswordUpdated', + 'onPasswordReset', + ], + PassphraseService::class => [ + 'setPassphraseForUser', ], ]; @@ -195,7 +202,9 @@ class ExceptionSerializer { return $this->editTrace($sensitiveValues, $traceLine); } foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) { - if (strpos($traceLine['function'], $sensitiveMethod) !== false) { + if (str_contains($traceLine['function'], $sensitiveMethod) + || (str_ends_with($sensitiveMethod, '*') + && str_starts_with($traceLine['function'], substr($sensitiveMethod, 0, -1)))) { return $this->editTrace($sensitiveValues, $traceLine); } } @@ -209,15 +218,15 @@ class ExceptionSerializer { }, $trace); } - private function removeValuesFromArgs($args, $values) { + private function removeValuesFromArgs($args, $values): array { $workArgs = []; - foreach ($args as $arg) { + foreach ($args as $key => $arg) { if (in_array($arg, $values, true)) { $arg = self::SENSITIVE_VALUE_PLACEHOLDER; } elseif (is_array($arg)) { $arg = $this->removeValuesFromArgs($arg, $values); } - $workArgs[] = $arg; + $workArgs[$key] = $arg; } return $workArgs; } @@ -269,7 +278,7 @@ class ExceptionSerializer { return $arg; } - public function serializeException(\Throwable $exception) { + public function serializeException(\Throwable $exception): array { $data = [ 'Exception' => get_class($exception), 'Message' => $exception->getMessage(), diff --git a/lib/private/Log/File.php b/lib/private/Log/File.php index a33667c9b68..ba428ba185b 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -1,38 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bart Visscher <bartv@thisnet.nl> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author duritong <peter.meier+github@immerda.ch> - * @author Georg Ehrke <oc.list@georgehrke.com> - * @author J0WI <J0WI@users.noreply.github.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Michael Gapczynski <GapczynskiM@gmail.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roland Tapken <roland@bitarbeiter.net> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Thomas Pulzer <t.pulzer@kniel.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Log; @@ -48,14 +19,15 @@ use OCP\Log\IWriter; */ class File extends LogDetails implements IWriter, IFileBased { - /** @var string */ - protected $logFile; - /** @var int */ - protected $logFileMode; - /** @var SystemConfig */ - private $config; + protected string $logFile; + + protected int $logFileMode; - public function __construct(string $path, string $fallbackPath, SystemConfig $config) { + public function __construct( + string $path, + string $fallbackPath, + private SystemConfig $config, + ) { parent::__construct($config); $this->logFile = $path; if (!file_exists($this->logFile)) { @@ -69,24 +41,21 @@ class File extends LogDetails implements IWriter, IFileBased { $this->logFile = $fallbackPath; } } - $this->config = $config; $this->logFileMode = $config->getValue('logfilemode', 0640); } /** * write a message in the log - * @param string $app * @param string|array $message - * @param int $level */ - public function write(string $app, $message, int $level) { + public function write(string $app, $message, int $level): void { $entry = $this->logDetailsAsJSON($app, $message, $level); $handle = @fopen($this->logFile, 'a'); if ($this->logFileMode > 0 && is_file($this->logFile) && (fileperms($this->logFile) & 0777) != $this->logFileMode) { @chmod($this->logFile, $this->logFileMode); } if ($handle) { - fwrite($handle, $entry."\n"); + fwrite($handle, $entry . "\n"); fclose($handle); } else { // Fall back to error_log @@ -102,12 +71,9 @@ class File extends LogDetails implements IWriter, IFileBased { /** * get entries from the log in reverse chronological order - * @param int $limit - * @param int $offset - * @return array */ - public function getEntries(int $limit = 50, int $offset = 0):array { - $minLevel = $this->config->getValue("loglevel", ILogger::WARN); + public function getEntries(int $limit = 50, int $offset = 0): array { + $minLevel = $this->config->getValue('loglevel', ILogger::WARN); $entries = []; $handle = @fopen($this->logFile, 'rb'); if ($handle) { @@ -125,7 +91,7 @@ class File extends LogDetails implements IWriter, IFileBased { // Add the first character if at the start of the file, // because it doesn't hit the else in the loop if ($pos == 0) { - $line = $ch.$line; + $line = $ch . $line; } $entry = json_decode($line); // Add the line as an entry if it is passed the offset and is equal or above the log level @@ -139,7 +105,7 @@ class File extends LogDetails implements IWriter, IFileBased { $line = ''; } } else { - $line = $ch.$line; + $line = $ch . $line; } $pos--; } @@ -148,9 +114,6 @@ class File extends LogDetails implements IWriter, IFileBased { return $entries; } - /** - * @return string - */ public function getLogFilePath():string { return $this->logFile; } diff --git a/lib/private/Log/LogDetails.php b/lib/private/Log/LogDetails.php index c82904d7cea..6063b25cef9 100644 --- a/lib/private/Log/LogDetails.php +++ b/lib/private/Log/LogDetails.php @@ -1,38 +1,17 @@ <?php + /** - * @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Julius Härtl <jus@bitgrid.net> - * @author Thomas Citharel <nextcloud@tcit.fr> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Log; use OC\SystemConfig; abstract class LogDetails { - /** @var SystemConfig */ - private $config; - - public function __construct(SystemConfig $config) { - $this->config = $config; + public function __construct( + private SystemConfig $config, + ) { } public function logDetails(string $app, $message, int $level): array { @@ -44,7 +23,7 @@ abstract class LogDetails { } catch (\Exception $e) { $timezone = new \DateTimeZone('UTC'); } - $time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", "")); + $time = \DateTime::createFromFormat('U.u', number_format(microtime(true), 4, '.', '')); if ($time === false) { $time = new \DateTime('now', $timezone); } else { @@ -59,7 +38,7 @@ abstract class LogDetails { $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; $method = is_string($request->getMethod()) ? $request->getMethod() : '--'; if ($this->config->getValue('installed', false)) { - $user = \OC_User::getUser() ? \OC_User::getUser() : '--'; + $user = \OC_User::getUser() ?: '--'; } else { $user = '--'; } @@ -81,6 +60,10 @@ abstract class LogDetails { 'userAgent', 'version' ); + $clientReqId = $request->getHeader('X-Request-Id'); + if ($clientReqId !== '') { + $entry['clientReqId'] = $clientReqId; + } if (is_array($message)) { // Exception messages are extracted and the exception is put into a separate field @@ -108,7 +91,7 @@ abstract class LogDetails { if (is_string($value)) { $testEncode = json_encode($value, JSON_UNESCAPED_SLASHES); if ($testEncode === false) { - $entry[$key] = utf8_encode($value); + $entry[$key] = mb_convert_encoding($value, 'UTF-8', mb_detect_encoding($value)); } } } diff --git a/lib/private/Log/LogFactory.php b/lib/private/Log/LogFactory.php index a5008f5ef77..ee6054b81f8 100644 --- a/lib/private/Log/LogFactory.php +++ b/lib/private/Log/LogFactory.php @@ -1,89 +1,45 @@ <?php + /** - * @copyright Copyright (c) 2018 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Johannes Ernst <jernst@indiecomputing.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Log; use OC\Log; use OC\SystemConfig; -use OCP\ILogger; use OCP\IServerContainer; use OCP\Log\ILogFactory; use OCP\Log\IWriter; use Psr\Log\LoggerInterface; class LogFactory implements ILogFactory { - /** @var IServerContainer */ - private $c; - /** @var SystemConfig */ - private $systemConfig; - - public function __construct(IServerContainer $c, SystemConfig $systemConfig) { - $this->c = $c; - $this->systemConfig = $systemConfig; + public function __construct( + private IServerContainer $c, + private SystemConfig $systemConfig, + ) { } /** * @throws \OCP\AppFramework\QueryException */ public function get(string $type):IWriter { - switch (strtolower($type)) { - case 'errorlog': - return new Errorlog($this->systemConfig); - case 'syslog': - return $this->c->resolve(Syslog::class); - case 'systemd': - return $this->c->resolve(Systemdlog::class); - case 'file': - return $this->buildLogFile(); - - // Backwards compatibility for old and fallback for unknown log types - case 'owncloud': - case 'nextcloud': - default: - return $this->buildLogFile(); - } - } - - public function getCustomLogger(string $path):ILogger { - $log = $this->buildLogFile($path); - return new Log($log, $this->systemConfig); + return match (strtolower($type)) { + 'errorlog' => new Errorlog($this->systemConfig), + 'syslog' => $this->c->resolve(Syslog::class), + 'systemd' => $this->c->resolve(Systemdlog::class), + 'file' => $this->buildLogFile(), + default => $this->buildLogFile(), + }; } protected function createNewLogger(string $type, string $tag, string $path): IWriter { - switch (strtolower($type)) { - case 'errorlog': - return new Errorlog($this->systemConfig, $tag); - case 'syslog': - return new Syslog($this->systemConfig, $tag); - case 'systemd': - return new Systemdlog($this->systemConfig, $tag); - case 'file': - case 'owncloud': - case 'nextcloud': - default: - return $this->buildLogFile($path); - } + return match (strtolower($type)) { + 'errorlog' => new Errorlog($this->systemConfig, $tag), + 'syslog' => new Syslog($this->systemConfig, $tag), + 'systemd' => new Systemdlog($this->systemConfig, $tag), + default => $this->buildLogFile($path), + }; } public function getCustomPsrLogger(string $path, string $type = 'file', string $tag = 'Nextcloud'): LoggerInterface { @@ -93,8 +49,8 @@ class LogFactory implements ILogFactory { ); } - protected function buildLogFile(string $logFile = ''):File { - $defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log'; + protected function buildLogFile(string $logFile = ''): File { + $defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'; if ($logFile === '') { $logFile = $this->systemConfig->getValue('logfile', $defaultLogFile); } diff --git a/lib/private/Log/PsrLoggerAdapter.php b/lib/private/Log/PsrLoggerAdapter.php index 80c4c187b13..79e9d4d9621 100644 --- a/lib/private/Log/PsrLoggerAdapter.php +++ b/lib/private/Log/PsrLoggerAdapter.php @@ -3,43 +3,44 @@ declare(strict_types=1); /** - * @copyright 2020 Christoph Wurst <christoph@winzerhof-wurst.at> - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Log; use OC\Log; +use OCP\EventDispatcher\IEventDispatcher; use OCP\ILogger; use OCP\Log\IDataLogger; use Psr\Log\InvalidArgumentException; use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; use Throwable; use function array_key_exists; use function array_merge; final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { - /** @var Log */ - private $logger; + public function __construct( + private Log $logger, + ) { + } + + public static function logLevelToInt(string $level): int { + return match ($level) { + LogLevel::ALERT => ILogger::ERROR, + LogLevel::CRITICAL => ILogger::ERROR, + LogLevel::DEBUG => ILogger::DEBUG, + LogLevel::EMERGENCY => ILogger::FATAL, + LogLevel::ERROR => ILogger::ERROR, + LogLevel::INFO => ILogger::INFO, + LogLevel::NOTICE => ILogger::INFO, + LogLevel::WARNING => ILogger::WARN, + default => throw new InvalidArgumentException('Unsupported custom log level'), + }; + } - public function __construct(Log $logger) { - $this->logger = $logger; + public function setEventDispatcher(IEventDispatcher $eventDispatcher): void { + $this->logger->setEventDispatcher($eventDispatcher); } private function containsThrowable(array $context): bool { @@ -49,23 +50,11 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { /** * System is unusable. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ public function emergency($message, array $context = []): void { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::FATAL, - ], - $context - )); - } else { - $this->logger->emergency($message, $context); - } + $this->log(LogLevel::EMERGENCY, (string)$message, $context); } /** @@ -74,23 +63,11 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { * Example: Entire website down, database unavailable, etc. This should * trigger the SMS alerts and wake you up. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function alert($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::ERROR, - ], - $context - )); - } else { - $this->logger->alert($message, $context); - } + public function alert($message, array $context = []): void { + $this->log(LogLevel::ALERT, (string)$message, $context); } /** @@ -98,46 +75,22 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { * * Example: Application component unavailable, unexpected exception. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function critical($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::ERROR, - ], - $context - )); - } else { - $this->logger->critical($message, $context); - } + public function critical($message, array $context = []): void { + $this->log(LogLevel::CRITICAL, (string)$message, $context); } /** * Runtime errors that do not require immediate action but should typically * be logged and monitored. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function error($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::ERROR, - ], - $context - )); - } else { - $this->logger->error($message, $context); - } + public function error($message, array $context = []): void { + $this->log(LogLevel::ERROR, (string)$message, $context); } /** @@ -146,45 +99,21 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { * Example: Use of deprecated APIs, poor use of an API, undesirable things * that are not necessarily wrong. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function warning($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::WARN, - ], - $context - )); - } else { - $this->logger->warning($message, $context); - } + public function warning($message, array $context = []): void { + $this->log(LogLevel::WARNING, (string)$message, $context); } /** * Normal but significant events. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function notice($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::INFO, - ], - $context - )); - } else { - $this->logger->notice($message, $context); - } + public function notice($message, array $context = []): void { + $this->log(LogLevel::NOTICE, (string)$message, $context); } /** @@ -192,72 +121,52 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { * * Example: User logs in, SQL logs. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function info($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::INFO, - ], - $context - )); - } else { - $this->logger->info($message, $context); - } + public function info($message, array $context = []): void { + $this->log(LogLevel::INFO, (string)$message, $context); } /** * Detailed debug information. * - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context */ - public function debug($message, array $context = []) { - if ($this->containsThrowable($context)) { - $this->logger->logException($context['exception'], array_merge( - [ - 'message' => $message, - 'level' => ILogger::DEBUG, - ], - $context - )); - } else { - $this->logger->debug($message, $context); - } + public function debug($message, array $context = []): void { + $this->log(LogLevel::DEBUG, (string)$message, $context); } /** * Logs with an arbitrary level. * * @param mixed $level - * @param string $message - * @param array $context - * - * @return void + * @param $message + * @param mixed[] $context * * @throws InvalidArgumentException */ - public function log($level, $message, array $context = []) { + public function log($level, $message, array $context = []): void { + if (is_string($level)) { + $level = self::logLevelToInt($level); + } + if (isset($context['level']) && is_string($context['level'])) { + $context['level'] = self::logLevelToInt($context['level']); + } if (!is_int($level) || $level < ILogger::DEBUG || $level > ILogger::FATAL) { - throw new InvalidArgumentException('Nextcloud allows only integer log levels'); + throw new InvalidArgumentException('Unsupported custom log level'); } if ($this->containsThrowable($context)) { $this->logger->logException($context['exception'], array_merge( [ - 'message' => $message, + 'message' => (string)$message, 'level' => $level, ], $context )); } else { - $this->logger->log($level, $message, $context); + $this->logger->log($level, (string)$message, $context); } } diff --git a/lib/private/Log/Rotate.php b/lib/private/Log/Rotate.php index 20bc3327f92..ee1593b87ac 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -1,30 +1,17 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bart Visscher <bartv@thisnet.nl> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Robin Appelman <robin@icewind.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Log; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\TimedJob; +use OCP\IConfig; use OCP\Log\RotationTrait; +use Psr\Log\LoggerInterface; /** * This rotates the current logfile to a new name, this way the total log usage @@ -32,18 +19,24 @@ use OCP\Log\RotationTrait; * For more professional log management set the 'logfile' config to a different * location and manage that with your own tools. */ -class Rotate extends \OCP\BackgroundJob\Job { +class Rotate extends TimedJob { use RotationTrait; - public function run($dummy) { - $systemConfig = \OC::$server->getSystemConfig(); - $this->filePath = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); + public function __construct(ITimeFactory $time) { + parent::__construct($time); + + $this->setInterval(3600); + } + + public function run($argument): void { + $config = \OCP\Server::get(IConfig::class); + $this->filePath = $config->getSystemValueString('logfile', $config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); - $this->maxSize = \OC::$server->getConfig()->getSystemValue('log_rotate_size', 100 * 1024 * 1024); + $this->maxSize = $config->getSystemValueInt('log_rotate_size', 100 * 1024 * 1024); if ($this->shouldRotateBySize()) { $rotatedFile = $this->rotate(); - $msg = 'Log file "'.$this->filePath.'" was over '.$this->maxSize.' bytes, moved to "'.$rotatedFile.'"'; - \OC::$server->getLogger()->warning($msg, ['app' => Rotate::class]); + $msg = 'Log file "' . $this->filePath . '" was over ' . $this->maxSize . ' bytes, moved to "' . $rotatedFile . '"'; + \OCP\Server::get(LoggerInterface::class)->info($msg, ['app' => Rotate::class]); } } } diff --git a/lib/private/Log/Syslog.php b/lib/private/Log/Syslog.php index f4ba857742f..46214599eb8 100644 --- a/lib/private/Log/Syslog.php +++ b/lib/private/Log/Syslog.php @@ -1,27 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bart Visscher <bartv@thisnet.nl> - * @author Julius Härtl <jus@bitgrid.net> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OC\Log; @@ -30,7 +12,7 @@ use OCP\ILogger; use OCP\Log\IWriter; class Syslog extends LogDetails implements IWriter { - protected $levels = [ + protected array $levels = [ ILogger::DEBUG => LOG_DEBUG, ILogger::INFO => LOG_INFO, ILogger::WARN => LOG_WARNING, @@ -38,12 +20,18 @@ class Syslog extends LogDetails implements IWriter { ILogger::FATAL => LOG_CRIT, ]; - public function __construct(SystemConfig $config, ?string $tag = null) { + private string $tag; + + public function __construct( + SystemConfig $config, + ?string $tag = null, + ) { parent::__construct($config); if ($tag === null) { - $tag = $config->getValue('syslog_tag', 'Nextcloud'); + $this->tag = $config->getValue('syslog_tag', 'Nextcloud'); + } else { + $this->tag = $tag; } - openlog($tag, LOG_PID | LOG_CONS, LOG_USER); } public function __destruct() { @@ -52,12 +40,11 @@ class Syslog extends LogDetails implements IWriter { /** * write a message in the log - * @param string $app * @param string|array $message - * @param int $level */ - public function write(string $app, $message, int $level) { + public function write(string $app, $message, int $level): void { $syslog_level = $this->levels[$level]; + openlog($this->tag, LOG_PID | LOG_CONS, LOG_USER); syslog($syslog_level, $this->logDetailsAsJSON($app, $message, $level)); } } diff --git a/lib/private/Log/Systemdlog.php b/lib/private/Log/Systemdlog.php index 8619cb5e4dd..ffea0511732 100644 --- a/lib/private/Log/Systemdlog.php +++ b/lib/private/Log/Systemdlog.php @@ -1,27 +1,8 @@ <?php + /** - * @copyright Copyright (c) 2018, Johannes Ernst - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Johannes Ernst <jernst@indiecomputing.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OC\Log; @@ -46,7 +27,7 @@ use OCP\Log\IWriter; // Syslog compatibility fields class Systemdlog extends LogDetails implements IWriter { - protected $levels = [ + protected array $levels = [ ILogger::DEBUG => 7, ILogger::INFO => 6, ILogger::WARN => 4, @@ -54,9 +35,12 @@ class Systemdlog extends LogDetails implements IWriter { ILogger::FATAL => 2, ]; - protected $syslogId; + protected string $syslogId; - public function __construct(SystemConfig $config, ?string $tag = null) { + public function __construct( + SystemConfig $config, + ?string $tag = null, + ) { parent::__construct($config); if (!function_exists('sd_journal_send')) { throw new HintException( @@ -71,14 +55,12 @@ class Systemdlog extends LogDetails implements IWriter { /** * Write a message to the log. - * @param string $app * @param string|array $message - * @param int $level */ - public function write(string $app, $message, int $level) { + public function write(string $app, $message, int $level): void { $journal_level = $this->levels[$level]; - sd_journal_send('PRIORITY='.$journal_level, - 'SYSLOG_IDENTIFIER='.$this->syslogId, + sd_journal_send('PRIORITY=' . $journal_level, + 'SYSLOG_IDENTIFIER=' . $this->syslogId, 'MESSAGE=' . $this->logDetailsAsJSON($app, $message, $level)); } } |