Skip to content

Commit bb3d308

Browse files
committed
feature #90 add global logger service that logs in job
1 parent f6f6826 commit bb3d308

File tree

8 files changed

+131
-3
lines changed

8 files changed

+131
-3
lines changed

src/batch-symfony-framework/composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
"symfony/dependency-injection": "^6.4|^7.0",
1919
"symfony/http-kernel": "^6.4|^7.0",
2020
"symfony/framework-bundle": "^6.4|^7.0",
21-
"yokai/batch": "^0.5.0"
21+
"yokai/batch": "^0.5.0",
22+
"psr/log": "^1.0|^2.0|^3.0"
2223
},
2324
"autoload": {
2425
"psr-4": {

src/batch-symfony-framework/docs/getting-started.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,18 @@ The job launcher that will be injected depends on the packages you have installe
104104
- if `yokai/batch-symfony-console` is installed, you will receive a `Yokai\Batch\Bridge\Symfony\Console\RunCommandJobLauncher`
105105
- otherwise you will receive a `Yokai\Batch\Launcher\SimpleJobLauncher`
106106

107+
108+
## Use the batchLogger
109+
In a symfony project, you can use the batchLogger with the symfony autowiring by naming your variable as `$yokaiBatchLogger`
110+
111+
```php
112+
use Psr\Log\LoggerInterface;
113+
114+
...
115+
__construct(private readonly LoggerInterface $yokaiBatchLogger) {
116+
}
117+
```
118+
107119
## On the same subject
108120

109121
- [What is a job execution storage ?](https://github.com/yokai-php/batch/blob/0.x/docs/domain/job-execution-storage.md)

src/batch-symfony-framework/src/DependencyInjection/YokaiBatchExtension.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Yokai\Batch\Bridge\Symfony\Framework\DependencyInjection;
66

77
use Composer\InstalledVersions;
8+
use Psr\Log\LoggerInterface;
89
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
910
use Symfony\Component\Config\FileLocator;
1011
use Symfony\Component\Config\Loader as ConfigLoader;
@@ -71,6 +72,7 @@ public function load(array $configs, ContainerBuilder $container): void
7172
JobLauncherInterface::class,
7273
\array_keys(\array_filter($launchers))[0] ?? 'yokai_batch.job_launcher.simple'
7374
);
75+
$container->registerAliasForArgument('yokai_batch.logger', LoggerInterface::class, 'yokaiBatchLogger');
7476
}
7577

7678
private function installed(string $package): bool
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?xml version="1.0" ?>
2+
3+
<container xmlns="http://symfony.com/schema/dic/services"
4+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5+
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
6+
7+
<services>
8+
<defaults public="false"/>
9+
10+
<service id="yokai_batch.logger" class="Yokai\Batch\Logger\BatchLogger">
11+
<tag name="kernel.event_listener" method="onPreExecute" event="Yokai\Batch\Event\PreExecuteEvent"/>
12+
<tag name="kernel.event_listener" method="onPostExecute" event="Yokai\Batch\Event\PostExecuteEvent"/>
13+
</service>
14+
15+
</services>
16+
</container>
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Logger;
6+
7+
use Psr\Log\AbstractLogger;
8+
use Psr\Log\InvalidArgumentException;
9+
use Psr\Log\LoggerInterface;
10+
use Psr\Log\NullLogger;
11+
use Stringable;
12+
use Yokai\Batch\Event\PostExecuteEvent;
13+
use Yokai\Batch\Event\PreExecuteEvent;
14+
15+
/**
16+
* BatchLogger allow to log with the jobExecutionLogger
17+
*/
18+
class BatchLogger extends AbstractLogger
19+
{
20+
private ?LoggerInterface $batchLogger = null;
21+
22+
/**
23+
* Access and remember the logger
24+
*/
25+
public function onPreExecute(PreExecuteEvent $event): void
26+
{
27+
$this->batchLogger = $event->getExecution()->getLogger();
28+
}
29+
30+
/**
31+
* Forget the logger
32+
*/
33+
public function onPostExecute(PostExecuteEvent $event): void
34+
{
35+
$this->batchLogger = null;
36+
}
37+
38+
/**
39+
* Log with the batchLogger defined in the PreExecuteEvent or with nullLogger if nothing remembered
40+
*
41+
* @param array<string, mixed> $context
42+
* @throws InvalidArgumentException
43+
*/
44+
public function log($level, Stringable|string $message, array $context = []): void
45+
{
46+
($this->batchLogger ?? new NullLogger())->log($level, $message, $context);
47+
}
48+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Tests\Logger;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Yokai\Batch\Event\PostExecuteEvent;
9+
use Yokai\Batch\Event\PreExecuteEvent;
10+
use Yokai\Batch\JobExecution;
11+
use Yokai\Batch\Logger\BatchLogger;
12+
use Yokai\Batch\Tests\Dummy\DebugEventDispatcher;
13+
14+
class BatchLoggerTest extends TestCase
15+
{
16+
public function testLaunch(): void
17+
{
18+
$dispatcher = new DebugEventDispatcher();
19+
$logger = new BatchLogger();
20+
21+
$dispatcher->addListener(PreExecuteEvent::class, [$logger, 'onPreExecute']);
22+
$dispatcher->addListener(PostExecuteEvent::class, [$logger, 'onPostExecute']);
23+
24+
$execution = JobExecution::createRoot('123', 'test.job_executor');
25+
26+
$logger->log('info', 'before');
27+
$preExecuteEvent = new PreExecuteEvent($execution);
28+
$dispatcher->dispatch($preExecuteEvent);
29+
30+
$logger->log('info', 'between');
31+
32+
$postExecuteEvent = new PostExecuteEvent($execution);
33+
$dispatcher->dispatch($postExecuteEvent);
34+
$logger->log('info', 'after');
35+
36+
self::assertStringNotContainsString('before', $execution->getLogs()->__toString());
37+
self::assertStringContainsString('between', $execution->getLogs()->__toString());
38+
self::assertStringNotContainsString('after', $execution->getLogs()->__toString());
39+
}
40+
}

tests/symfony/src/Job/Country/CountryJob.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Yokai\Batch\Sources\Tests\Symfony\App\Job\Country;
66

7+
use Psr\Log\LoggerInterface;
78
use Symfony\Component\HttpKernel\KernelInterface;
89
use Yokai\Batch\Bridge\OpenSpout\Writer\FlatFileWriter;
910
use Yokai\Batch\Bridge\Symfony\Framework\JobWithStaticNameInterface;
@@ -56,14 +57,18 @@ final class CountryJob extends AbstractDecoratedJob implements
5657
private ItemWriterInterface $writer;
5758
private array $countries = [];
5859
private bool $flushed = false;
60+
private LoggerInterface $yokaiBatchLogger;
5961

6062
public static function getJobName(): string
6163
{
6264
return 'country';
6365
}
6466

65-
public function __construct(JobExecutionStorageInterface $executionStorage, KernelInterface $kernel)
66-
{
67+
public function __construct(
68+
JobExecutionStorageInterface $executionStorage,
69+
KernelInterface $kernel,
70+
LoggerInterface $yokaiBatchLogger
71+
) {
6772
$writePath = fn(string $format) => new StaticValueParameterAccessor(
6873
ARTIFACT_DIR . '/symfony/country/countries.' . $format
6974
);
@@ -81,6 +86,7 @@ public function __construct(JobExecutionStorageInterface $executionStorage, Kern
8186
new FlatFileWriter($writePath('csv'), null, null, $headers),
8287
new JsonLinesWriter($writePath('jsonl')),
8388
]);
89+
$this->yokaiBatchLogger = $yokaiBatchLogger;
8490

8591
parent::__construct(
8692
new ItemJob(
@@ -95,6 +101,8 @@ public function __construct(JobExecutionStorageInterface $executionStorage, Kern
95101

96102
public function process(mixed $item): array
97103
{
104+
$this->yokaiBatchLogger->log('info', 'log process');
105+
98106
return ['iso2' => $item['code'], $item['_key'] => $item['value']];
99107
}
100108

tests/symfony/tests/CountryJobSet.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ static function (JobExecution $execution) {
7474
'{"iso2":"GB","iso3":"GBR","name":"United Kingdom","continent":"EU","currency":"GBP","phone":"44"}',
7575
$jsonl
7676
);
77+
Assert::assertStringContainsString('log process', $execution->getLogs()->__toString());
7778
},
7879
];
7980
}

0 commit comments

Comments
 (0)