Restructure Logger to new paradigm

This commit is contained in:
Philipp 2021-10-23 12:22:27 +02:00
parent 0fe545ab17
commit 184f6cc255
No known key found for this signature in database
GPG key ID: 24A7501396EB5432
28 changed files with 219 additions and 169 deletions

View file

@ -1,192 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Introspection;
use Mockery\MockInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
abstract class AbstractLoggerTest extends MockedTest
{
use LoggerDataTrait;
const LOGLINE = '/.* \[.*\]: .* \{.*\"file\":\".*\".*,.*\"line\":\d*,.*\"function\":\".*\".*,.*\"uid\":\".*\".*}/';
const FILE = 'test';
const LINE = 666;
const FUNC = 'myfunction';
/**
* @var Introspection|MockInterface
*/
protected $introspection;
/**
* Returns the content of the current logger instance
*
* @return string
*/
abstract protected function getContent();
/**
* Returns the current logger instance
*
* @param string $level the default loglevel
*
* @return LoggerInterface
*/
abstract protected function getInstance($level = LogLevel::DEBUG);
protected function setUp(): void
{
parent::setUp();
$this->introspection = \Mockery::mock(Introspection::class);
$this->introspection->shouldReceive('getRecord')->andReturn([
'file' => self::FILE,
'line' => self::LINE,
'function' => self::FUNC
]);
}
public function assertLogline($string)
{
self::assertRegExp(self::LOGLINE, $string);
}
public function assertLoglineNums($assertNum, $string)
{
self::assertEquals($assertNum, preg_match_all(self::LOGLINE, $string));
}
/**
* Test if the logger works correctly
*/
public function testNormal()
{
$logger = $this->getInstance();
$logger->emergency('working!');
$logger->alert('working too!');
$logger->debug('and now?');
$logger->notice('message', ['an' => 'context']);
$text = $this->getContent();
self::assertLogline($text);
self::assertLoglineNums(4, $text);
}
/**
* Test if a log entry is correctly interpolated
*/
public function testPsrInterpolate()
{
$logger = $this->getInstance();
$logger->emergency('A {psr} test', ['psr' => 'working']);
$logger->alert('An {array} test', ['array' => ['it', 'is', 'working']]);
$text = $this->getContent();
self::assertStringContainsString('A working test', $text);
self::assertStringContainsString('An ["it","is","working"] test', $text);
}
/**
* Test if a log entry contains all necessary information
*/
public function testContainsInformation()
{
$logger = $this->getInstance();
$logger->emergency('A test');
$text = $this->getContent();
self::assertStringContainsString('"file":"' . self::FILE . '"', $text);
self::assertStringContainsString('"line":' . self::LINE, $text);
self::assertStringContainsString('"function":"' . self::FUNC . '"', $text);
}
/**
* Test if the minimum level is working
*/
public function testMinimumLevel()
{
$logger = $this->getInstance(LogLevel::NOTICE);
$logger->emergency('working');
$logger->alert('working');
$logger->error('working');
$logger->warning('working');
$logger->notice('working');
$logger->info('not working');
$logger->debug('not working');
$text = $this->getContent();
self::assertLoglineNums(5, $text);
}
/**
* Test with different logging data
* @dataProvider dataTests
*/
public function testDifferentTypes($function, $message, array $context)
{
$logger = $this->getInstance();
$logger->$function($message, $context);
$text = $this->getContent();
self::assertLogline($text);
self::assertStringContainsString(@json_encode($context), $text);
}
/**
* Test a message with an exception
*/
public function testExceptionHandling()
{
$e = new \Exception("Test String", 123);
$eFollowUp = new \Exception("FollowUp", 456, $e);
$assertion = $eFollowUp->__toString();
$logger = $this->getInstance();
$logger->alert('test', ['e' => $eFollowUp]);
$text = $this->getContent();
self::assertLogline($text);
self::assertStringContainsString(@json_encode($assertion), $this->getContent());
}
public function testNoObjectHandling()
{
$logger = $this->getInstance();
$logger->alert('test', ['e' => ['test' => 'test']]);
$text = $this->getContent();
self::assertLogline($text);
self::assertStringContainsString('test', $this->getContent());
}
}

View file

@ -1,71 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
trait LoggerDataTrait
{
public function dataTests()
{
return [
'emergency' => [
'function' => 'emergency',
'message' => 'test',
'context' => ['a' => 'context'],
],
'alert' => [
'function' => 'alert',
'message' => 'test {test}',
'context' => ['a' => 'context', 2 => 'so', 'test' => 'works'],
],
'critical' => [
'function' => 'critical',
'message' => 'test crit 2345',
'context' => ['a' => 'context', 'wit' => ['more', 'array']],
],
'error' => [
'function' => 'error',
'message' => 2.554,
'context' => [],
],
'warning' => [
'function' => 'warning',
'message' => 'test warn',
'context' => ['a' => 'context'],
],
'notice' => [
'function' => 'notice',
'message' => 2346,
'context' => ['a' => 'context'],
],
'info' => [
'function' => 'info',
'message' => null,
'context' => ['a' => 'context'],
],
'debug' => [
'function' => 'debug',
'message' => true,
'context' => ['a' => false],
],
];
}
}

View file

@ -1,83 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\ProfilerLogger;
use Friendica\Util\Profiler;
use Mockery\MockInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class ProfilerLoggerTest extends MockedTest
{
use LoggerDataTrait;
/**
* @var LoggerInterface|MockInterface
*/
private $logger;
/**
* @var Profiler|MockInterface
*/
private $profiler;
protected function setUp(): void
{
parent::setUp();
$this->logger = \Mockery::mock(LoggerInterface::class);
$this->profiler = \Mockery::mock(Profiler::class);
}
/**
* Test if the profiler is profiling data
* @dataProvider dataTests
* @doesNotPerformAssertions
*/
public function testProfiling($function, $message, array $context)
{
$logger = new ProfilerLogger($this->logger, $this->profiler);
$this->logger->shouldReceive($function)->with($message, $context)->once();
$this->profiler->shouldReceive('startRecording')->with('file')->once();
$this->profiler->shouldReceive('stopRecording');
$this->profiler->shouldReceive('saveTimestamp');
$logger->$function($message, $context);
}
/**
* Test the log() function
* @doesNotPerformAssertions
*/
public function testProfilingLog()
{
$logger = new ProfilerLogger($this->logger, $this->profiler);
$this->logger->shouldReceive('log')->with(LogLevel::WARNING, 'test', ['a' => 'context'])->once();
$this->profiler->shouldReceive('startRecording')->with('file')->once();
$this->profiler->shouldReceive('stopRecording');
$this->profiler->shouldReceive('saveTimestamp');
$logger->log(LogLevel::WARNING, 'test', ['a' => 'context']);
}
}

View file

@ -1,211 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Util\FileSystem;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Logger\StreamLogger;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
use Psr\Log\LogLevel;
class StreamLoggerTest extends AbstractLoggerTest
{
use VFSTrait;
/**
* @var vfsStreamFile
*/
private $logfile;
/**
* @var Filesystem
*/
private $fileSystem;
protected function setUp(): void
{
parent::setUp();
$this->setUpVfsDir();
$this->fileSystem = new FileSystem();
}
/**
* {@@inheritdoc}
*/
protected function getInstance($level = LogLevel::DEBUG)
{
$this->logfile = vfsStream::newFile('friendica.log')
->at($this->root);
$logger = new StreamLogger('test', $this->logfile->url(), $this->introspection, $this->fileSystem, $level);
return $logger;
}
/**
* {@inheritdoc}
*/
protected function getContent()
{
return $this->logfile->getContent();
}
/**
* Test if a stream is working
*/
public function testStream()
{
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
$filehandler = fopen($logfile->url(), 'ab');
$logger = new StreamLogger('test', $filehandler, $this->introspection, $this->fileSystem);
$logger->emergency('working');
$text = $logfile->getContent();
self::assertLogline($text);
}
/**
* Test if the close statement is working
*/
public function testClose()
{
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
$logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem);
$logger->emergency('working');
$logger->close();
// close doesn't affect
$logger->emergency('working too');
$text = $logfile->getContent();
self::assertLoglineNums(2, $text);
}
/**
* Test when a file isn't set
*/
public function testNoUrl()
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage("Missing stream URL.");
$logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem);
$logger->emergency('not working');
}
/**
* Test when a file cannot be opened
*/
public function testWrongUrl()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageMatches("/The stream or file .* could not be opened: .* /");
$logfile = vfsStream::newFile('friendica.log')
->at($this->root)->chmod(0);
$logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem);
$logger->emergency('not working');
}
/**
* Test when the directory cannot get created
*/
public function testWrongDir()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageMatches("/Directory .* cannot get created: .* /");
static::markTestIncomplete('We need a platform independent way to set directory to readonly');
$logger = new StreamLogger('test', '/$%/wrong/directory/file.txt', $this->introspection, $this->fileSystem);
$logger->emergency('not working');
}
/**
* Test when the minimum level is not valid
*/
public function testWrongMinimumLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new StreamLogger('test', 'file.text', $this->introspection, $this->fileSystem, 'NOPE');
}
/**
* Test when the minimum level is not valid
*/
public function testWrongLogLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
$logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem);
$logger->log('NOPE', 'a test');
}
/**
* Test when the file is null
*/
public function testWrongFile()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("A stream must either be a resource or a string.");
$logger = new StreamLogger('test', null, $this->introspection, $this->fileSystem);
}
/**
* Test a relative path
* @doesNotPerformAssertions
*/
public function testRealPath()
{
static::markTestSkipped('vfsStream isn\'t compatible with chdir, so not testable.');
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
chdir($this->root->getChild('logs')->url());
$logger = new StreamLogger('test', '../friendica.log' , $this->introspection, $this->fileSystem);
$logger->info('Test');
}
}

View file

@ -1,113 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Util\Logger\SyslogLogger;
use Psr\Log\LogLevel;
class SyslogLoggerTest extends AbstractLoggerTest
{
/**
* @var SyslogLoggerWrapper
*/
private $logger;
protected function setUp(): void
{
parent::setUp();
$this->introspection->shouldReceive('addClasses')->with([SyslogLogger::class]);
}
/**
* {@inheritdoc}
*/
protected function getContent()
{
return $this->logger->getContent();
}
/**
* {@inheritdoc}
*/
protected function getInstance($level = LogLevel::DEBUG)
{
$this->logger = new SyslogLoggerWrapper('test', $this->introspection, $level);
return $this->logger;
}
/**
* Test when the minimum level is not valid
*/
public function testWrongMinimumLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection, 'NOPE');
}
/**
* Test when the minimum level is not valid
*/
public function testWrongLogLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection);
$logger->log('NOPE', 'a test');
}
/**
* Test when the logfacility is wrong (string)
*/
public function testServerException()
{
if (PHP_MAJOR_VERSION < 8) {
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageMatches("/Can\'t open syslog for ident \".*\" and facility \".*\": .* /");
} else {
$this->expectException(\TypeError::class);
$this->expectExceptionMessage("openlog(): Argument #3 (\$facility) must be of type int, string given");
}
$logger = new SyslogLoggerWrapper('test', $this->introspection, LogLevel::DEBUG, null, 'a string');
$logger->emergency('not working');
}
/**
* Test the close() method
* @doesNotPerformAssertions
*/
public function testClose()
{
$logger = new SyslogLoggerWrapper('test', $this->introspection);
$logger->emergency('test');
$logger->close();
// Reopened itself
$logger->emergency('test');
}
}

View file

@ -1,60 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Util\Introspection;
use Friendica\Util\Logger\SyslogLogger;
use Psr\Log\LogLevel;
/**
* Wraps the SyslogLogger for replacing the syslog call with a string field.
*/
class SyslogLoggerWrapper extends SyslogLogger
{
private $content;
public function __construct($channel, Introspection $introspection, $level = LogLevel::NOTICE, $logOpts = LOG_PID, $logFacility = LOG_USER)
{
parent::__construct($channel, $introspection, $level, $logOpts, $logFacility);
$this->content = '';
}
/**
* Gets the content from the wrapped Syslog
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* {@inheritdoc}
* @noinspection PhpMissingParentCallCommonInspection
*/
protected function syslogWrapper($level, $entry)
{
$this->content .= $entry . PHP_EOL;
}
}

View file

@ -1,52 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\VoidLogger;
use Psr\Log\LogLevel;
class VoidLoggerTest extends MockedTest
{
use LoggerDataTrait;
/**
* Test if the profiler is profiling data
* @dataProvider dataTests
* @doesNotPerformAssertions
*/
public function testNormal($function, $message, array $context)
{
$logger = new VoidLogger();
$logger->$function($message, $context);
}
/**
* Test the log() function
* @doesNotPerformAssertions
*/
public function testProfilingLog()
{
$logger = new VoidLogger();
$logger->log(LogLevel::WARNING, 'test', ['a' => 'context']);
}
}

View file

@ -1,137 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @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 <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\WorkerLogger;
use Psr\Log\LoggerInterface;
class WorkerLoggerTest extends MockedTest
{
private function assertUid($uid, $length = 7)
{
self::assertRegExp('/^[a-zA-Z0-9]{' . $length . '}+$/', $uid);
}
/**
* Test the a id with length zero
*
*/
public function testGetWorkerIdZero()
{
$this->expectException(\Error::class);
$logger = \Mockery::mock(LoggerInterface::class);
new WorkerLogger($logger, 'test', 0);
}
/**
* Test the generated Uid
*/
public function testGetWorkerId()
{
$logger = \Mockery::mock(LoggerInterface::class);
for ($i = 1; $i < 14; $i++) {
$workLogger = new WorkerLogger($logger, 'test', $i);
$uid = $workLogger->getWorkerId();
self::assertUid($uid, $i);
}
}
public function dataTest()
{
return [
'info' => [
'func' => 'info',
'msg' => 'the alert',
'context' => [],
],
'alert' => [
'func' => 'alert',
'msg' => 'another alert',
'context' => ['test' => 'it'],
],
'critical' => [
'func' => 'critical',
'msg' => 'Critical msg used',
'context' => ['test' => 'it', 'more' => 0.24545],
],
'error' => [
'func' => 'error',
'msg' => 21345623,
'context' => ['test' => 'it', 'yet' => true],
],
'warning' => [
'func' => 'warning',
'msg' => 'another alert' . 123523 . 324.54534 . 'test',
'context' => ['test' => 'it', 2 => 'nope'],
],
'notice' => [
'func' => 'notice',
'msg' => 'Notice' . ' alert' . true . 'with' . '\'strange\'' . 1.24. 'behavior',
'context' => ['test' => 'it'],
],
'debug' => [
'func' => 'debug',
'msg' => 'at last a debug',
'context' => ['test' => 'it'],
],
];
}
/**
* Test the WorkerLogger with different log calls
* @dataProvider dataTest
*/
public function testEmergency($func, $msg, $context = [])
{
$logger = \Mockery::mock(LoggerInterface::class);
$workLogger = new WorkerLogger($logger, 'test');
$testContext = $context;
$testContext['worker_id'] = $workLogger->getWorkerId();
$testContext['worker_cmd'] = 'test';
self::assertUid($testContext['worker_id']);
$logger
->shouldReceive($func)
->with($msg, $testContext)
->once();
$workLogger->$func($msg, $context);
}
/**
* Test the WorkerLogger with
*/
public function testLog()
{
$logger = \Mockery::mock(LoggerInterface::class);
$workLogger = new WorkerLogger($logger, 'test');
$context = $testContext = ['test' => 'it'];
$testContext['worker_id'] = $workLogger->getWorkerId();
$testContext['worker_cmd'] = 'test';
self::assertUid($testContext['worker_id']);
$logger
->shouldReceive('log')
->with('debug', 'a test', $testContext)
->once();
$workLogger->log('debug', 'a test', $context);
}
}