Skip to content

Commit

Permalink
Implement logger factory rfc (#298)
Browse files Browse the repository at this point in the history
  • Loading branch information
PabloKowalczyk authored Apr 15, 2020
1 parent 65f0fbe commit 3f7c8f5
Show file tree
Hide file tree
Showing 19 changed files with 912 additions and 306 deletions.
56 changes: 49 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ The following task will be run every hour at the 15th minute
// ...
$task = $schedule->run(PHP_BINARY . ' feedmecookie.php');
$task
->hourlyAt('15')
->hourlyAt('15');
// ...
```
>hourlyOn('15') could have been used instead of hourlyAt('15') with the same result
Expand All @@ -253,7 +253,7 @@ The following task will be run Monday at 13:30
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php');
$task
->weeklyOn(1,'13:30')
->weeklyOn(1,'13:30');
// ...
```
>Sunday is considered day 0 of the week.
Expand All @@ -264,7 +264,7 @@ If we wished for the task to run on Tuesday (day 2 of the week) at 09:00 we woul
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php');
$task
->weeklyOn(2,'09:00')
->weeklyOn(2,'09:00');
// ...
```

Expand All @@ -274,7 +274,7 @@ The following task will be run on the second of the month at 20:00
// ...
$task = $schedule->run(PHP_BINARY . ' datenight.php');
$task
->MonthlyOn(2, '20:00')
->MonthlyOn(2, '20:00');
// ...
```

Expand Down Expand Up @@ -370,7 +370,7 @@ This is the correct way of using weekday methods:
// ...
$task = $schedule->run(PHP_BINARY . ' startofwork.php');
$task
->mondays();
->mondays()
->at('13:30');

// ...
Expand All @@ -382,7 +382,7 @@ $task

Dynamic methods give us a wide variety of frequency options on the fly. We just need to follow this pattern:

```php
```text
every[NumberInCamelCaseWords]Minute|Hour|Day|Months?
```

Expand Down Expand Up @@ -671,6 +671,48 @@ As a result, if the execution of an event is unsuccessful for some reasons, the

It is also possible to send the errors as emails to a group of recipients by setting `email_error` and `mailer` settings in the configuration file.

## Custom logger

To use your own logger create class implementing `\Crunz\Application\Service\LoggerFactoryInterface`, for example:

```php
<?php

namespace Vendor\Package;

use Crunz\Application\Service\ConfigurationInterface;
use Crunz\Application\Service\LoggerFactoryInterface;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

final class MyEchoLoggerFactory implements LoggerFactoryInterface
{
public function create(ConfigurationInterface $configuration): LoggerInterface
{
return new class extends AbstractLogger {
/** @inheritDoc */
public function log(
$level,
$message,
array $context = array()
) {
echo "crunz.{$level}: {$message}";
}
};
}
}
```

then use this class name in config:

```yaml
# ./crunz.yml file

logger_factory: 'Vendor\Package\MyEchoLoggerFactory'
```
Done.
## Pre-Process and Post-Process Hooks
There are times when we want to do some kind of operations before and after an event. This is possible by attaching pre-process and post-process callbacks to the respective event.
Expand Down Expand Up @@ -727,7 +769,7 @@ vendor/bin/crunz --help

One of these commands is `crunz schedule:list`, which lists the defined tasks (in collected `*.Tasks.php` files) in a tabular format.

```php
```text
vendor/bin/crunz schedule:list
+---+---------------+-------------+--------------------+
Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"require": {
"php": "^7.2",
"dragonmantank/cron-expression": "^2.0",
"monolog/monolog": "^1.19",
"opis/closure": "^3.5",
"swiftmailer/swiftmailer": "^6.0",
"symfony/config": "^3.4.5 || ^4.3 || ^5.0",
Expand Down
4 changes: 4 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Crunz\Application\Query\TaskInformation\TaskInformationHandler;
use Crunz\Application\Service\ClosureSerializerInterface;
use Crunz\Application\Service\ConfigurationInterface;
use Crunz\Clock\Clock;
use Crunz\Clock\ClockInterface;
use Crunz\Configuration\Configuration;
use Crunz\Configuration\ConfigurationParser;
use Crunz\Configuration\ConfigurationParserInterface;
Expand Down Expand Up @@ -68,6 +70,7 @@
LoaderInterface::class => Loader::class,
CronExpressionFactoryInterface::class => DragonmantankCronExpressionFactory::class,
ClosureSerializerInterface::class => OpisClosureSerializer::class,
ClockInterface::class => Clock::class,
];

/* @var ContainerBuilder $container */
Expand Down Expand Up @@ -183,6 +186,7 @@
new Reference(ConfigurationInterface::class),
new Reference(Timezone::class),
new Reference(ConsoleLoggerInterface::class),
new Reference(ClockInterface::class),
]
)
;
Expand Down
15 changes: 15 additions & 0 deletions src/Application/Service/LoggerFactoryInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Crunz\Application\Service;

use Psr\Log\LoggerInterface;

/**
* @experimental
*/
interface LoggerFactoryInterface
{
public function create(ConfigurationInterface $configuration): LoggerInterface;
}
7 changes: 7 additions & 0 deletions src/Configuration/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Crunz\Configuration;

use Crunz\Infrastructure\Psr\Logger\PsrStreamLoggerFactory;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

Expand Down Expand Up @@ -43,6 +44,12 @@ public function getConfigTreeBuilder(): TreeBuilder
->info('Whether configured "timezone" will be used for logs')
->end()

->scalarNode('logger_factory')
->defaultValue(PsrStreamLoggerFactory::class)
->cannotBeEmpty()
->info("Class name implementing 'LoggerFactoryInterface'. Use it to provider your own logger.")
->end()

->booleanNode('log_errors')
->defaultFalse()
->info('Flag for logging errors' . PHP_EOL)
Expand Down
103 changes: 30 additions & 73 deletions src/EventRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,20 @@
use Crunz\Application\Service\ConfigurationInterface;
use Crunz\HttpClient\HttpClientInterface;
use Crunz\Logger\ConsoleLoggerInterface;
use Crunz\Logger\Logger;
use Crunz\Logger\LoggerFactory;
use Crunz\Pinger\PingableInterface;
use Symfony\Component\Console\Output\OutputInterface;

class EventRunner
{
/**
* Schedule objects.
*
* @var Schedule[]
*/
/** @var Schedule[] */
protected $schedules = [];
/**
* Instance of the invoker class.
*
* @var \Crunz\Invoker
*/
/** @var \Crunz\Invoker */
protected $invoker;
/**
* The Logger.
*
* @var \Crunz\Logger\Logger
*/
/** @var \Crunz\Logger\Logger|null */
protected $logger;
/**
* The Mailer.
*
* @var \Crunz\Mailer
*/
/** @var \Crunz\Mailer */
protected $mailer;
/** @var OutputInterface */
private $output;
Expand All @@ -48,9 +33,6 @@ class EventRunner
/** @var ConsoleLoggerInterface */
private $consoleLogger;

/**
* Instantiate the event runner.
*/
public function __construct(
Invoker $invoker,
ConfigurationInterface $configuration,
Expand All @@ -59,16 +41,6 @@ public function __construct(
HttpClientInterface $httpClient,
ConsoleLoggerInterface $consoleLogger
) {
$outputLogFile = $configuration->get('output_log_file');
$errorLogFile = $configuration->get('errors_log_file');

$this->logger = $loggerFactory->create(
[
// Logging streams
'info' => $outputLogFile,
'error' => $errorLogFile,
]
);
$this->invoker = $invoker;
$this->mailer = $mailer;
$this->configuration = $configuration;
Expand All @@ -77,11 +49,7 @@ public function __construct(
$this->consoleLogger = $consoleLogger;
}

/**
* Handle an array of Schedule objects.
*
* @param Schedule[] $schedules
*/
/** @param Schedule[] $schedules */
public function handle(OutputInterface $output, array $schedules = []): void
{
$this->schedules = $schedules;
Expand All @@ -106,13 +74,12 @@ public function handle(OutputInterface $output, array $schedules = []): void
$this->manageStartedEvents();
}

/**
* Run an event process.
*
* @param \Crunz\Event $event
*/
protected function start(Event $event): void
{
$this->logger = $this->loggerFactory
->create()
;

// if sendOutputTo or appendOutputTo have been specified
if (!$event->nullOutput()) {
// if sendOutputTo then truncate the log file if it exists
Expand All @@ -124,12 +91,7 @@ protected function start(Event $event): void
}
}
// Create an instance of the Logger specific to the event
$event->logger = $this->loggerFactory->create(
[
// Logging streams
'info' => $event->output,
]
);
$event->logger = $this->loggerFactory->create();
}

$this->consoleLogger
Expand All @@ -142,9 +104,6 @@ protected function start(Event $event): void
$event->start();
}

/**
* Manage the running processes.
*/
protected function manageStartedEvents(): void
{
while ($this->schedules) {
Expand Down Expand Up @@ -214,8 +173,6 @@ protected function manageStartedEvents(): void
}

/**
* Invoke an array of callables.
*
* @param \Closure[] $callbacks
* @param array<mixed,mixed> $parameters
*
Expand All @@ -240,7 +197,9 @@ protected function handleOutput(Event $event): void
;

if ($logOutput) {
$this->logger->info($this->formatEventOutput($event));
$this->logger()
->info($this->formatEventOutput($event))
;
$logged = true;
}
if (!$event->nullOutput()) {
Expand All @@ -262,11 +221,6 @@ protected function handleOutput(Event $event): void
}
}

/**
* Handle errors.
*
* @param \Crunz\Event $event
*/
protected function handleError(Event $event): void
{
$logErrors = $this->configuration
Expand All @@ -277,7 +231,9 @@ protected function handleError(Event $event): void
;

if ($logErrors) {
$this->logger->error($this->formatEventError($event));
$this->logger()
->error($this->formatEventError($event))
;
} else {
$output = $event->wholeOutput();

Expand Down Expand Up @@ -307,13 +263,7 @@ protected function formatEventOutput(Event $event)
. PHP_EOL;
}

/**
* Format the event error message.
*
* @param \Crunz\Event $event
*
* @return string
*/
/** @return string */
protected function formatEventError(Event $event)
{
return $event->description
Expand All @@ -325,11 +275,7 @@ protected function formatEventError(Event $event)
. PHP_EOL;
}

/**
* Display content.
*
* @param string|null $output
*/
/** @param string|null $output */
protected function display($output): void
{
$this->output
Expand Down Expand Up @@ -362,4 +308,15 @@ private function pingAfter(PingableInterface $schedule): void
$this->httpClient
->ping($schedule->getPingAfterUrl());
}

private function logger(): Logger
{
if (null === $this->logger) {
$this->logger = $this->loggerFactory
->create()
;
}

return $this->logger;
}
}
Loading

0 comments on commit 3f7c8f5

Please sign in to comment.