Skip to content

Commit

Permalink
Merge branch 'log_to_specific_event_log_file' into log_to_specific_ev…
Browse files Browse the repository at this point in the history
…ent_log_file-2.3.x
  • Loading branch information
drjayvee committed May 6, 2021
2 parents 364aa90 + f07569e commit cb1a425
Show file tree
Hide file tree
Showing 10 changed files with 198 additions and 6 deletions.
7 changes: 7 additions & 0 deletions src/Application/Service/ConfigurationInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,12 @@ interface ConfigurationInterface
*/
public function get(string $key, $default = null);

/**
* Set a parameter based on a key.
*
* @param mixed $value
*/
public function withNewEntry(string $key, $value): ConfigurationInterface;

public function getSourcePath(): string;
}
29 changes: 29 additions & 0 deletions src/Configuration/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,35 @@ public function get(string $key, $default = null)
return $value;
}

/**
* Set a parameter based on key/value.
*
* @param mixed $value
*/
public function withNewEntry(string $key, $value): ConfigurationInterface
{
$newConfiguration = clone $this;

if (null === $newConfiguration->config) {
$newConfiguration->config = $newConfiguration->configurationParser
->parseConfig();
}

$parts = \explode('.', $key);

if (\count($parts) > 1) {
if (\array_key_exists($parts[0], $newConfiguration->config) && \is_array($newConfiguration->config[$parts[0]])) {
$newConfiguration->config[$parts[0]][$parts[1]] = $value;
} else {
$newConfiguration->config[$parts[0]] = [$parts[1] => $value];
}
} else {
$newConfiguration->config[$key] = $value;
}

return $newConfiguration;
}

public function getSourcePath(): string
{
$sourcePath = Path::create(
Expand Down
14 changes: 8 additions & 6 deletions src/EventRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ protected function start(Event $event): void
}
}
// Create an instance of the Logger specific to the event
$event->logger = $this->loggerFactory->create();
$event->logger = $this->loggerFactory->createEvent($event->output);
}

$this->consoleLogger
Expand Down Expand Up @@ -196,16 +196,18 @@ protected function handleOutput(Event $event): void
->get('log_output')
;

if ($logOutput) {
if (!$event->nullOutput()) {
$event->logger->info($this->formatEventOutput($event));
$logged = true;
}

if ($logOutput && !$logged) {
$this->logger()
->info($this->formatEventOutput($event))
;
$logged = true;
}
if (!$event->nullOutput()) {
$event->logger->info($this->formatEventOutput($event));
$logged = true;
}

if (!$logged) {
$this->display($event->getOutputStream());
}
Expand Down
11 changes: 11 additions & 0 deletions src/Logger/LoggerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ public function create(): Logger
return new Logger($innerLogger);
}

public function createEvent(string $output): Logger
{
$this->initializeLoggerFactory();
$eventConfiguration = $this->configuration->withNewEntry('output_log_file', $output);
$innerLogger = $this->loggerFactory
->create($eventConfiguration)
;

return new Logger($innerLogger);
}

private function initializeLoggerFactory(): void
{
if (null === $this->loggerFactory) {
Expand Down
27 changes: 27 additions & 0 deletions tests/EndToEnd/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,33 @@ public function test_outputs_are_logged(): void
);
}

public function test_event_logging_override(): void
{
$envBuilder = $this->createEnvironmentBuilder()
->addTask('CustomOutputTasks')
->withConfig(
[
'log_output' => true,
'output_log_file' => 'main.log',
]
)
;
$environment = $envBuilder->createEnvironment();
$logPath = $environment->rootDirectory() . DIRECTORY_SEPARATOR;

$process = $environment->runCrunzCommand('schedule:run');

$this->assertEmpty($process->getOutput());

$this->assertFileDoesNotExist("$logPath/main.log");

$this->assertFileExists("$logPath/custom.log");
$this->assertStringContainsString(
'Usage: php',
file_get_contents("$logPath/custom.log")
);
}

private function assertLogRecord(
string $logRecord,
string $level,
Expand Down
20 changes: 20 additions & 0 deletions tests/TestCase/FakeConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ public function get(string $key, $default = null)
return $value;
}

/** {@inheritdoc} */
public function withNewEntry(string $key, $value): ConfigurationInterface
{
$newConfiguration = clone $this;

$parts = \explode('.', $key);

if (\count($parts) > 1) {
if (\array_key_exists($parts[0], $newConfiguration->config) && \is_array($newConfiguration->config[$parts[0]])) {
$newConfiguration->config[$parts[0]][$parts[1]] = $value;
} else {
$newConfiguration->config[$parts[0]] = [$parts[1] => $value];
}
} else {
$newConfiguration->config[$key] = $value;
}

return $newConfiguration;
}

public function getSourcePath(): string
{
return (string) $this->get('source', 'tasks');
Expand Down
34 changes: 34 additions & 0 deletions tests/Unit/Configuration/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,40 @@ public function source_path_fallback_to_tasks_directory(): void
$this->assertSame($expectedPath->toString(), $configuration->getSourcePath());
}

/** @test */
public function set_configuration_key_value(): void
{
$cwd = \sys_get_temp_dir();
$sourcePath = Path::fromStrings('app', 'tasks');
$configuration = $this->createConfiguration(['source' => $sourcePath->toString()], $cwd);

$keyName = 'test_key';
$expectedValue = 'test_value';

$newConfiguration = $configuration->withNewEntry($keyName, $expectedValue);

$this->assertSame($newConfiguration->get($keyName), $expectedValue);
}

/** @test */
public function set_configuration_key_array(): void
{
$cwd = \sys_get_temp_dir();
$sourcePath = Path::fromStrings('app', 'tasks');
$configuration = $this->createConfiguration(['source' => $sourcePath->toString()], $cwd);

$arrayName = 'test_array';
$keyName = 'test_key';
$expectedValue = 'test_value';

$newConfiguration = $configuration->withNewEntry("{$arrayName}.{$keyName}", $expectedValue);
$expectedArray = $newConfiguration->get($arrayName);

$this->assertIsArray($expectedArray);
$this->assertArrayHasKey($keyName, $expectedArray);
$this->assertSame($expectedArray[$keyName], $expectedValue);
}

/** @param array<string,string|array> $config */
private function createConfiguration(array $config = [], string $cwd = ''): Configuration
{
Expand Down
30 changes: 30 additions & 0 deletions tests/Unit/EventRunnerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,36 @@ public function url_is_pinged_after(): void
$eventRunner->handle($output, [$schedule]);
}

public function test_event_logging_configuration(): void
{
$logTarget = 'event.log';

// create schedule with event that changes logging configuration
$schedule = new Schedule();
$schedule->run('php -v')
->appendOutputTo($logTarget)
;

// mock the LoggerFactory
$loggerFactory = $this->createMock(LoggerFactory::class);
$loggerFactory->expects($this->once())
->method('createEvent')
->with($logTarget);

// create an EventRunner to handle the Schedule
$eventRunner = new EventRunner(
$this->createMock(Invoker::class),
new FakeConfiguration(),
$this->createMock(Mailer::class),
$loggerFactory,
$this->createMock(HttpClientInterface::class),
$this->createMock(ConsoleLoggerInterface::class)
);

$output = $this->createMock(OutputInterface::class);
$eventRunner->handle($output, [$schedule]);
}

public function test_lock_is_released_on_error(): void
{
$output = $this->createMock(OutputInterface::class);
Expand Down
16 changes: 16 additions & 0 deletions tests/Unit/Logger/LoggerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
namespace Crunz\Tests\Unit\Logger;

use Crunz\Clock\Clock;
use Crunz\Event;
use Crunz\Exception\CrunzException;
use Crunz\Logger\LoggerFactory;
use Crunz\Task\Timezone;
use Crunz\Tests\TestCase\FakeConfiguration;
use Crunz\Tests\TestCase\Logger\NullLogger;
use Crunz\Tests\TestCase\TemporaryFile;
use PHPUnit\Framework\TestCase;

final class LoggerFactoryTest extends TestCase
Expand All @@ -23,6 +25,20 @@ public function test_logger_factory_creates_logger(): void
$this->expectNotToPerformAssertions();
}

public function test_logger_factory_creates_event_logger(): void
{
$loggerFactory = $this->createLoggerFactory();

$tempFile = new TemporaryFile();

$e = new Event('1', 'php foo');
$e->output = $tempFile->filePath();

$loggerFactory->createEvent($e->output);

$this->expectNotToPerformAssertions();
}

public function test_wrong_logger_class_throws_exception(): void
{
$loggerFactory = $this->createLoggerFactory(['logger_factory' => 'Wrong\Class']);
Expand Down
16 changes: 16 additions & 0 deletions tests/resources/tasks/CustomOutputTasks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

use Crunz\Schedule;

$scheduler = new Schedule();

$scheduler
->run('php --help')
->description('Custom logging test')
->everyMinute()
->appendOutputTo('custom.log')
;

return $scheduler;

0 comments on commit cb1a425

Please sign in to comment.