Skip to content

Commit d491f71

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

File tree

8 files changed

+147
-3
lines changed

8 files changed

+147
-3
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@
4949
"symfony/security-bundle": "^6.4|^7.0",
5050
"symfony/translation": "^6.4|^7.0",
5151
"symfony/twig-bundle": "^6.4|^7.0",
52-
"symplify/easy-coding-standard": "^11.3"
52+
"symplify/easy-coding-standard": "^11.3",
53+
"symfony/monolog-bundle": "^3.10"
5354
},
5455
"replace": {
5556
"yokai/batch": "self.version",

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,19 @@ 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+
## Define a custom BatchLogger
109+
In a symfony project, a monolog handler could be declared as of:
110+
```yaml
111+
# config/packages/monolog.yaml
112+
monolog:
113+
handlers:
114+
batch:
115+
type: service
116+
id: service.to.be.defined
117+
```
118+
119+
107120
## On the same subject
108121

109122
- [What is a job execution storage ?](https://github.com/yokai-php/batch/blob/0.x/docs/domain/job-execution-storage.md)
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: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
/*
3+
* This file is part of the Tucania project.
4+
*
5+
* Copyright (C) Tucania (https://www.tucania.com/) - All Rights Reserved
6+
*
7+
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
8+
*/
9+
declare(strict_types=1);
10+
11+
namespace Yokai\Batch\Logger;
12+
13+
use Psr\Log\AbstractLogger;
14+
use Psr\Log\InvalidArgumentException;
15+
use Psr\Log\LoggerInterface;
16+
use Psr\Log\NullLogger;
17+
use Stringable;
18+
use Yokai\Batch\Event\PostExecuteEvent;
19+
use Yokai\Batch\Event\PreExecuteEvent;
20+
21+
/**
22+
* BatchLogger allow to log with the jobExecutionLogger
23+
*/
24+
class BatchLogger extends AbstractLogger
25+
{
26+
private ?LoggerInterface $batchLogger = null;
27+
28+
/**
29+
* Access and remember the logger
30+
*/
31+
public function onPreExecute(PreExecuteEvent $event): void
32+
{
33+
$this->batchLogger = $event->getExecution()->getLogger();
34+
}
35+
36+
/**
37+
* Forget the logger
38+
*/
39+
public function onPostExecute(PostExecuteEvent $event): void
40+
{
41+
$this->batchLogger = null;
42+
}
43+
44+
/**
45+
* Log with the batchLogger defined in the PreExecuteEvent or with nullLogger if nothing remembered
46+
*
47+
* @param array<string, mixed> $context
48+
* @throws InvalidArgumentException
49+
*/
50+
public function log($level, Stringable|string $message, array $context = []): void
51+
{
52+
($this->batchLogger ?? new NullLogger())->log($level, $message, $context);
53+
}
54+
}
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 $batchLogger;
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 $batchLogger
71+
) {
6772
$writePath = fn(string $format) => new StaticValueParameterAccessor(
6873
ARTIFACT_DIR . '/symfony/country/countries.' . $format
6974
);
@@ -91,10 +96,13 @@ public function __construct(JobExecutionStorageInterface $executionStorage, Kern
9196
$executionStorage
9297
),
9398
);
99+
$this->batchLogger = $batchLogger;
94100
}
95101

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

tests/symfony/src/Kernel.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
88
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
99
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
10+
use Symfony\Bundle\MonologBundle\MonologBundle;
1011
use Symfony\Bundle\SecurityBundle\SecurityBundle;
1112
use Symfony\Bundle\TwigBundle\TwigBundle;
1213
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
@@ -31,6 +32,7 @@ public function registerBundles(): iterable
3132
yield new TwigBundle();
3233
yield new SecurityBundle();
3334
yield new YokaiBatchBundle();
35+
yield new MonologBundle();
3436
}
3537

3638
public function getProjectDir(): string
@@ -108,6 +110,15 @@ protected function configureContainer(ContainerConfigurator $container): void
108110
],
109111
]);
110112

113+
$container->extension('monolog', [
114+
'handlers' => [
115+
'batch' => [
116+
'type' => 'service',
117+
'id' => 'yokai_batch.logger',
118+
],
119+
],
120+
]);
121+
111122
$container->services()
112123
->set('logger', Logger::class)
113124
->args([null, '%kernel.logs_dir%/test.log', null, new Reference(RequestStack::class)])

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)