Refactors lib/private/Log.

Mainly using PHP8's constructor property promotion.

Signed-off-by: Faraz Samapoor <fsa@adlas.at>
pull/39039/head
Faraz Samapoor 2023-06-28 09:23:43 +07:00 committed by Faraz Samapoor
parent 918aacdf1a
commit 9fa9975bc9
10 changed files with 77 additions and 149 deletions

@ -36,10 +36,9 @@ use Psr\Log\LoggerInterface;
use Throwable; use Throwable;
class ErrorHandler { class ErrorHandler {
private LoggerInterface $logger; public function __construct(
private LoggerInterface $logger,
public function __construct(LoggerInterface $logger) { ) {
$this->logger = $logger;
} }
/** /**
@ -94,20 +93,11 @@ class ErrorHandler {
} }
private static function errnoToLogLevel(int $errno): int { private static function errnoToLogLevel(int $errno): int {
switch ($errno) { return match ($errno) {
case E_USER_WARNING: E_USER_WARNING => ILogger::WARN,
return ILogger::WARN; E_DEPRECATED, E_USER_DEPRECATED => ILogger::DEBUG,
E_USER_NOTICE => ILogger::INFO,
case E_DEPRECATED: default => ILogger::ERROR,
case E_USER_DEPRECATED: };
return ILogger::DEBUG;
case E_USER_NOTICE:
return ILogger::INFO;
case E_USER_ERROR:
default:
return ILogger::ERROR;
}
} }
} }

@ -32,22 +32,19 @@ use OC\SystemConfig;
use OCP\Log\IWriter; use OCP\Log\IWriter;
class Errorlog extends LogDetails implements IWriter { class Errorlog extends LogDetails implements IWriter {
/** @var string */ public function __construct(
protected $tag; SystemConfig $config,
protected string $tag = 'nextcloud',
public function __construct(SystemConfig $config, string $tag = 'nextcloud') { ) {
parent::__construct($config); parent::__construct($config);
$this->tag = $tag;
} }
/** /**
* Write a message in the log * Write a message in the log
* *
* @param string $app
* @param string|array $message * @param string|array $message
* @param int $level
*/ */
public function write(string $app, $message, int $level) { public function write(string $app, $message, int $level): void {
error_log('[' . $this->tag . ']['.$app.']['.$level.'] '.$this->logDetailsAsJSON($app, $message, $level)); error_log('[' . $this->tag . ']['.$app.']['.$level.'] '.$this->logDetailsAsJSON($app, $message, $level));
} }
} }

@ -112,11 +112,9 @@ class ExceptionSerializer {
]; ];
/** @var SystemConfig */ public function __construct(
private $systemConfig; private SystemConfig $systemConfig,
) {
public function __construct(SystemConfig $systemConfig) {
$this->systemConfig = $systemConfig;
} }
protected array $methodsWithSensitiveParametersByClass = [ protected array $methodsWithSensitiveParametersByClass = [
@ -219,7 +217,7 @@ class ExceptionSerializer {
}, $trace); }, $trace);
} }
private function removeValuesFromArgs($args, $values) { private function removeValuesFromArgs($args, $values): array {
$workArgs = []; $workArgs = [];
foreach ($args as $arg) { foreach ($args as $arg) {
if (in_array($arg, $values, true)) { if (in_array($arg, $values, true)) {
@ -279,7 +277,7 @@ class ExceptionSerializer {
return $arg; return $arg;
} }
public function serializeException(\Throwable $exception) { public function serializeException(\Throwable $exception): array {
$data = [ $data = [
'Exception' => get_class($exception), 'Exception' => get_class($exception),
'Message' => $exception->getMessage(), 'Message' => $exception->getMessage(),

@ -48,14 +48,15 @@ use OCP\Log\IWriter;
*/ */
class File extends LogDetails implements IWriter, IFileBased { class File extends LogDetails implements IWriter, IFileBased {
/** @var string */ protected string $logFile;
protected $logFile;
/** @var int */
protected $logFileMode;
/** @var SystemConfig */
private $config;
public function __construct(string $path, string $fallbackPath, SystemConfig $config) { protected int $logFileMode;
public function __construct(
string $path,
string $fallbackPath,
private SystemConfig $config,
) {
parent::__construct($config); parent::__construct($config);
$this->logFile = $path; $this->logFile = $path;
if (!file_exists($this->logFile)) { if (!file_exists($this->logFile)) {
@ -69,17 +70,14 @@ class File extends LogDetails implements IWriter, IFileBased {
$this->logFile = $fallbackPath; $this->logFile = $fallbackPath;
} }
} }
$this->config = $config;
$this->logFileMode = $config->getValue('logfilemode', 0640); $this->logFileMode = $config->getValue('logfilemode', 0640);
} }
/** /**
* write a message in the log * write a message in the log
* @param string $app
* @param string|array $message * @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); $entry = $this->logDetailsAsJSON($app, $message, $level);
$handle = @fopen($this->logFile, 'a'); $handle = @fopen($this->logFile, 'a');
if ($this->logFileMode > 0 && is_file($this->logFile) && (fileperms($this->logFile) & 0777) != $this->logFileMode) { if ($this->logFileMode > 0 && is_file($this->logFile) && (fileperms($this->logFile) & 0777) != $this->logFileMode) {
@ -102,11 +100,8 @@ class File extends LogDetails implements IWriter, IFileBased {
/** /**
* get entries from the log in reverse chronological order * 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 { public function getEntries(int $limit = 50, int $offset = 0): array {
$minLevel = $this->config->getValue("loglevel", ILogger::WARN); $minLevel = $this->config->getValue("loglevel", ILogger::WARN);
$entries = []; $entries = [];
$handle = @fopen($this->logFile, 'rb'); $handle = @fopen($this->logFile, 'rb');
@ -148,9 +143,6 @@ class File extends LogDetails implements IWriter, IFileBased {
return $entries; return $entries;
} }
/**
* @return string
*/
public function getLogFilePath():string { public function getLogFilePath():string {
return $this->logFile; return $this->logFile;
} }

@ -28,11 +28,9 @@ namespace OC\Log;
use OC\SystemConfig; use OC\SystemConfig;
abstract class LogDetails { abstract class LogDetails {
/** @var SystemConfig */ public function __construct(
private $config; private SystemConfig $config,
) {
public function __construct(SystemConfig $config) {
$this->config = $config;
} }
public function logDetails(string $app, $message, int $level): array { public function logDetails(string $app, $message, int $level): array {

@ -33,57 +33,37 @@ use OCP\Log\IWriter;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class LogFactory implements ILogFactory { class LogFactory implements ILogFactory {
/** @var IServerContainer */ public function __construct(
private $c; private IServerContainer $c,
/** @var SystemConfig */ private SystemConfig $systemConfig,
private $systemConfig; ) {
public function __construct(IServerContainer $c, SystemConfig $systemConfig) {
$this->c = $c;
$this->systemConfig = $systemConfig;
} }
/** /**
* @throws \OCP\AppFramework\QueryException * @throws \OCP\AppFramework\QueryException
*/ */
public function get(string $type):IWriter { public function get(string $type):IWriter {
switch (strtolower($type)) { return match (strtolower($type)) {
case 'errorlog': 'errorlog' => new Errorlog($this->systemConfig),
return new Errorlog($this->systemConfig); 'syslog' => $this->c->resolve(Syslog::class),
case 'syslog': 'systemd' => $this->c->resolve(Systemdlog::class),
return $this->c->resolve(Syslog::class); 'file' => $this->buildLogFile(),
case 'systemd': default => $this->buildLogFile(),
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 { public function getCustomLogger(string $path): ILogger {
$log = $this->buildLogFile($path); $log = $this->buildLogFile($path);
return new Log($log, $this->systemConfig); return new Log($log, $this->systemConfig);
} }
protected function createNewLogger(string $type, string $tag, string $path): IWriter { protected function createNewLogger(string $type, string $tag, string $path): IWriter {
switch (strtolower($type)) { return match (strtolower($type)) {
case 'errorlog': 'errorlog' => new Errorlog($this->systemConfig, $tag),
return new Errorlog($this->systemConfig, $tag); 'syslog' => new Syslog($this->systemConfig, $tag),
case 'syslog': 'systemd' => new Systemdlog($this->systemConfig, $tag),
return new Syslog($this->systemConfig, $tag); default => $this->buildLogFile($path),
case 'systemd': };
return new Systemdlog($this->systemConfig, $tag);
case 'file':
case 'owncloud':
case 'nextcloud':
default:
return $this->buildLogFile($path);
}
} }
public function getCustomPsrLogger(string $path, string $type = 'file', string $tag = 'Nextcloud'): LoggerInterface { public function getCustomPsrLogger(string $path, string $type = 'file', string $tag = 'Nextcloud'): LoggerInterface {
@ -93,7 +73,7 @@ class LogFactory implements ILogFactory {
); );
} }
protected function buildLogFile(string $logFile = ''):File { protected function buildLogFile(string $logFile = ''): File {
$defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log'; $defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
if ($logFile === '') { if ($logFile === '') {
$logFile = $this->systemConfig->getValue('logfile', $defaultLogFile); $logFile = $this->systemConfig->getValue('logfile', $defaultLogFile);

@ -36,14 +36,12 @@ use function array_key_exists;
use function array_merge; use function array_merge;
final class PsrLoggerAdapter implements LoggerInterface, IDataLogger { final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
/** @var Log */ public function __construct(
private $logger; private Log $logger,
) {
public function __construct(Log $logger) {
$this->logger = $logger;
} }
public function setEventDispatcher(IEventDispatcher $eventDispatcher) { public function setEventDispatcher(IEventDispatcher $eventDispatcher): void {
$this->logger->setEventDispatcher($eventDispatcher); $this->logger->setEventDispatcher($eventDispatcher);
} }
@ -55,9 +53,6 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* System is unusable. * System is unusable.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function emergency($message, array $context = []): void { public function emergency($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
@ -80,11 +75,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* trigger the SMS alerts and wake you up. * trigger the SMS alerts and wake you up.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function alert($message, array $context = []) { public function alert($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -104,11 +96,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* Example: Application component unavailable, unexpected exception. * Example: Application component unavailable, unexpected exception.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function critical($message, array $context = []) { public function critical($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -127,11 +116,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* be logged and monitored. * be logged and monitored.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function error($message, array $context = []) { public function error($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -152,11 +138,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* that are not necessarily wrong. * that are not necessarily wrong.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function warning($message, array $context = []) { public function warning($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -174,11 +157,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* Normal but significant events. * Normal but significant events.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function notice($message, array $context = []) { public function notice($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -198,11 +178,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* Example: User logs in, SQL logs. * Example: User logs in, SQL logs.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function info($message, array $context = []) { public function info($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -220,11 +197,8 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* Detailed debug information. * Detailed debug information.
* *
* @param string $message * @param string $message
* @param array $context
*
* @return void
*/ */
public function debug($message, array $context = []) { public function debug($message, array $context = []): void {
if ($this->containsThrowable($context)) { if ($this->containsThrowable($context)) {
$this->logger->logException($context['exception'], array_merge( $this->logger->logException($context['exception'], array_merge(
[ [
@ -243,13 +217,10 @@ final class PsrLoggerAdapter implements LoggerInterface, IDataLogger {
* *
* @param mixed $level * @param mixed $level
* @param string $message * @param string $message
* @param array $context
*
* @return void
* *
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function log($level, $message, array $context = []) { public function log($level, $message, array $context = []): void {
if (!is_int($level) || $level < ILogger::DEBUG || $level > ILogger::FATAL) { if (!is_int($level) || $level < ILogger::DEBUG || $level > ILogger::FATAL) {
throw new InvalidArgumentException('Nextcloud allows only integer log levels'); throw new InvalidArgumentException('Nextcloud allows only integer log levels');
} }

@ -35,7 +35,7 @@ use OCP\Log\RotationTrait;
class Rotate extends \OCP\BackgroundJob\Job { class Rotate extends \OCP\BackgroundJob\Job {
use RotationTrait; use RotationTrait;
public function run($dummy) { public function run($dummy): void {
$systemConfig = \OC::$server->getSystemConfig(); $systemConfig = \OC::$server->getSystemConfig();
$this->filePath = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); $this->filePath = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log');

@ -30,7 +30,7 @@ use OCP\ILogger;
use OCP\Log\IWriter; use OCP\Log\IWriter;
class Syslog extends LogDetails implements IWriter { class Syslog extends LogDetails implements IWriter {
protected $levels = [ protected array $levels = [
ILogger::DEBUG => LOG_DEBUG, ILogger::DEBUG => LOG_DEBUG,
ILogger::INFO => LOG_INFO, ILogger::INFO => LOG_INFO,
ILogger::WARN => LOG_WARNING, ILogger::WARN => LOG_WARNING,
@ -38,7 +38,10 @@ class Syslog extends LogDetails implements IWriter {
ILogger::FATAL => LOG_CRIT, ILogger::FATAL => LOG_CRIT,
]; ];
public function __construct(SystemConfig $config, ?string $tag = null) { public function __construct(
SystemConfig $config,
?string $tag = null,
) {
parent::__construct($config); parent::__construct($config);
if ($tag === null) { if ($tag === null) {
$tag = $config->getValue('syslog_tag', 'Nextcloud'); $tag = $config->getValue('syslog_tag', 'Nextcloud');
@ -52,11 +55,9 @@ class Syslog extends LogDetails implements IWriter {
/** /**
* write a message in the log * write a message in the log
* @param string $app
* @param string|array $message * @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]; $syslog_level = $this->levels[$level];
syslog($syslog_level, $this->logDetailsAsJSON($app, $message, $level)); syslog($syslog_level, $this->logDetailsAsJSON($app, $message, $level));
} }

@ -46,7 +46,7 @@ use OCP\Log\IWriter;
// Syslog compatibility fields // Syslog compatibility fields
class Systemdlog extends LogDetails implements IWriter { class Systemdlog extends LogDetails implements IWriter {
protected $levels = [ protected array $levels = [
ILogger::DEBUG => 7, ILogger::DEBUG => 7,
ILogger::INFO => 6, ILogger::INFO => 6,
ILogger::WARN => 4, ILogger::WARN => 4,
@ -54,9 +54,12 @@ class Systemdlog extends LogDetails implements IWriter {
ILogger::FATAL => 2, 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); parent::__construct($config);
if (!function_exists('sd_journal_send')) { if (!function_exists('sd_journal_send')) {
throw new HintException( throw new HintException(
@ -71,11 +74,9 @@ class Systemdlog extends LogDetails implements IWriter {
/** /**
* Write a message to the log. * Write a message to the log.
* @param string $app
* @param string|array $message * @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]; $journal_level = $this->levels[$level];
sd_journal_send('PRIORITY='.$journal_level, sd_journal_send('PRIORITY='.$journal_level,
'SYSLOG_IDENTIFIER='.$this->syslogId, 'SYSLOG_IDENTIFIER='.$this->syslogId,