浏览代码

finalize monolog configuration for multi env

Olivier Massot 1 年之前
父节点
当前提交
c8712848dc
共有 5 个文件被更改,包括 152 次插入209 次删除
  1. 0 111
      config/packages/docker/monolog.yaml
  2. 103 0
      config/packages/monolog.yaml
  3. 0 86
      config/packages/prod/monolog.yaml
  4. 1 1
      doc/cron.md
  5. 48 11
      src/Commands/CronCommand.php

+ 0 - 111
config/packages/docker/monolog.yaml

@@ -1,111 +0,0 @@
-# Voir doc/logging.md
-monolog:
-    channels: ['cron']
-    handlers:
-        # sorties standards (stdout, stderr, console)
-        stderr:
-            type: stream
-            path: php://stderr
-            level: error
-            channels: ["!event", "!doctrine", "!cron"]
-        console:
-            type: console
-            process_psr_3_messages: false
-            level: debug
-            channels: ["!event", "!doctrine", "!console"]
-
-        # email en cas d'erreurs critiques, sauf erreurs 404 / 405
-#        critical:
-#            type: fingers_crossed
-#            action_level: critical
-#            excluded_http_codes: [ 404, 405 ]
-#            handler: deduplicated
-#        deduplicated:
-#            type: deduplication
-#            handler: mailer
-#        mailer:
-#            type: symfony_mailer
-#            from_email: "process@opentalent.fr"
-#            to_email: "exploitation@opentalent.fr"
-#            subject: AP2I - Critical Error Occurred
-#            level: critical
-#            formatter: monolog.formatter.html
-#            content_type: text/html
-
-        # logging fichier
-        file_main:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%env(LOG_FILE_NAME)%.main.log"
-            level: debug
-            max_files: 3
-            channels: [php, doctrine, http_client, elastica]
-        file_auth:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%kernel.environment%.auth.log"
-            level: debug
-            max_files: 3
-            channels: security
-
-
-
-        ### --- Cron-Jobs ---
-        cron:
-            type: group
-            members: [cron_file]
-            channels: cron
-        # Log fichier (niveau debug)
-        cron_file:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%kernel.environment%.cron.log"
-            level: debug
-            max_files: 7
-            formatter: monolog.formatter.message
-
-        # Rapport par mail
-        cron_info:
-            type:           fingers_crossed
-            action_level:   info
-            handler:        cron_info_deduplicated
-            channels: ['cron']
-        cron_info_deduplicated:
-            type: deduplication
-            # the time in seconds during which duplicate entries are discarded (default: 60)
-            time: 10
-            handler: cron_info_mailer
-        cron_info_mailer:
-            type:           symfony_mailer
-            from_email:     "cron@opentalent.fr"
-            to_email:       "exploitation@opentalent.fr"
-            subject:        "Cron - Execution Report"
-            level:          info
-            content_type:   text/html
-
-        # Log par mail en cas d'erreur critique
-        cron_critical:
-            type:           fingers_crossed
-            action_level:   critical
-            handler:        cron_critical_deduplicated
-        cron_critical_deduplicated:
-            type: deduplication
-            # the time in seconds during which duplicate entries are discarded (default: 60)
-            time: 10
-            handler: cron_critical_mailer
-        cron_critical_mailer:
-            type:           symfony_mailer
-            from_email:     "cron@opentalent.fr"
-            to_email:       "exploitation@opentalent.fr"
-            subject:        "Cron - Critical Error"
-            level:          critical
-            formatter:      monolog.formatter.html
-            content_type:   text/html
-
-
-
-        # uncomment to get logging in your browser
-        # you may have to allow bigger header sizes in your Web server configuration
-        #firephp:
-        #    type: firephp
-        #    level: info
-        #chromephp:
-        #    type: chromephp
-        #    level: info

+ 103 - 0
config/packages/monolog.yaml

@@ -1,3 +1,106 @@
 monolog:
     channels:
         - deprecation # Deprecations are logged in the dedicated "deprecation" channel when it exists
+        - cron
+
+    handlers:
+        # sorties standards (stdout, stderr, console)
+        stderr:
+            type: stream
+            path: php://stderr
+            level: error
+            channels: [ "!event", "!doctrine", "!cron" ]
+        console:
+            type: console
+            process_psr_3_messages: false
+            level: debug
+            channels: [ "!event", "!doctrine", "!console" ]
+
+        # logging fichier
+        file_main:
+            type: rotating_file
+            path: "%kernel.logs_dir%/%env(LOG_FILE_NAME)%.main.log"
+            level: debug
+            max_files: 3
+            channels: [php, doctrine, http_client, elastica]
+        file_auth:
+            type: rotating_file
+            path: "%kernel.logs_dir%/%kernel.environment%.auth.log"
+            level: debug
+            max_files: 3
+            channels: security
+
+        # email en cas d'erreurs critiques, sauf erreurs 404 / 405
+        #        critical:
+        #            type: fingers_crossed
+        #            action_level: critical
+        #            excluded_http_codes: [ 404, 405 ]
+        #            handler: deduplicated
+        #        deduplicated:
+        #            type: deduplication
+        #            handler: mailer
+        #        mailer:
+        #            type: symfony_mailer
+        #            from_email: "process@opentalent.fr"
+        #            to_email: "exploitation@opentalent.fr"
+        #            subject: AP2I - Critical Error Occurred
+        #            level: critical
+        #            formatter: monolog.formatter.html
+        #            content_type: text/html
+
+        ### --- Cron-Jobs ---
+        # Log fichier (niveau debug)
+        cron_file:
+            type: rotating_file
+            path: "%kernel.logs_dir%/%kernel.environment%.cron.log"
+            level: debug
+            max_files: 7
+            formatter: monolog.formatter.message
+            channels: [cron]
+
+        # Rapport par mail
+        cron_info:
+            type:           fingers_crossed
+            action_level:   info
+            handler:        cron_info_deduplicated
+            channels: ['cron']
+        cron_info_deduplicated:
+            type: deduplication
+            # the time in seconds during which duplicate entries are discarded (default: 60)
+            time: 10
+            handler: cron_info_mailer
+        cron_info_mailer:
+            type:           symfony_mailer
+            from_email:     "cron@opentalent.fr"
+            to_email:       "exploitation@opentalent.fr"
+            subject:        "Cron - Execution Report"
+            level:          info
+            content_type:   text/html
+
+        # Log par mail en cas d'erreur critique
+        cron_critical:
+            type:           fingers_crossed
+            action_level:   critical
+            handler:        cron_critical_deduplicated
+        cron_critical_deduplicated:
+            type: deduplication
+            # the time in seconds during which duplicate entries are discarded (default: 60)
+            time: 10
+            handler: cron_critical_mailer
+        cron_critical_mailer:
+            type:           symfony_mailer
+            from_email:     "cron@opentalent.fr"
+            to_email:       "exploitation@opentalent.fr"
+            subject:        "Cron - Critical Error"
+            level:          critical
+            formatter:      monolog.formatter.html
+            content_type:   text/html
+
+        # uncomment to get logging in your browser
+        # you may have to allow bigger header sizes in your Web server configuration
+        #firephp:
+        #    type: firephp
+        #    level: info
+        #chromephp:
+        #    type: chromephp
+        #    level: info

+ 0 - 86
config/packages/prod/monolog.yaml

@@ -1,86 +0,0 @@
-# Voir doc/logging.md
-monolog:
-    channels: ['cron']
-    handlers:
-        # sorties standards (stdout, stderr, console)
-        stderr:
-            type: stream
-            path: php://stderr
-            level: error
-            channels: ["!event", "!doctrine"]
-        console:
-            type: console
-            process_psr_3_messages: false
-            level: debug
-            channels: ["!event", "!doctrine", "!console"]
-
-        # email en cas d'erreurs critiques, sauf erreurs 404 / 405
-        #        critical:
-        #            type: fingers_crossed
-        #            action_level: critical
-        #            excluded_http_codes: [ 404, 405 ]
-        #            handler: deduplicated
-        #        deduplicated:
-        #            type: deduplication
-        #            handler: mailer
-        #        mailer:
-        #            type: symfony_mailer
-        #            from_email: "process@opentalent.fr"
-        #            to_email: "exploitation@opentalent.fr"
-        #            subject: AP2I - Critical Error Occurred
-        #            level: critical
-        #            formatter: monolog.formatter.html
-        #            content_type: text/html
-
-        # logging fichier
-        file_main:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%env(LOG_FILE_NAME)%.main.log"
-            level: debug
-            max_files: 3
-            channels: [php, doctrine, http_client, elastica]
-        file_auth:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%kernel.environment%.auth.log"
-            level: debug
-            max_files: 3
-            channels: security
-
-        # logs dédiés à l'exécution des cron-jobs
-        cron:
-            type: group
-            members: [cron_file]
-            channels: cron
-        cron_file:
-            type: rotating_file
-            path: "%kernel.logs_dir%/%kernel.environment%.cron.log"
-            level: debug
-            max_files: 7
-            formatter: monolog.formatter.message
-#        cron_critical:
-#            type:           fingers_crossed
-#            action_level:   critical
-#            handler:        cron_deduplicated
-#        cron_deduplicated:
-#            type: deduplication
-#            # the time in seconds during which duplicate entries are discarded (default: 60)
-#            time: 10
-#            handler: cron_mailer
-#        cron_mailer:
-#            type:           symfony_mailer
-#            from_email:     "process@opentalent.fr"
-#            to_email:       "exploitation@opentalent.fr"
-#            subject:        "Cron - Critical Error"
-#            level:          error
-#            formatter:      monolog.formatter.html
-#            content_type:   text/html
-
-
-        # uncomment to get logging in your browser
-        # you may have to allow bigger header sizes in your Web server configuration
-        #firephp:
-        #    type: firephp
-        #    level: info
-        #chromephp:
-        #    type: chromephp
-        #    level: info

+ 1 - 1
doc/cron.md

@@ -15,7 +15,7 @@ Pour plus d'informations :
 
     bin/console ot:cron --help
 
-> A noter : tous les jobs implémentent une méthode preview qui peut être exécutée en passant l'option -p, --preview 
+> À noter : tous les jobs implémentent une méthode preview qui peut être exécutée en passant l'option -p, --preview 
 > à la commande.
 
 ## Créer un nouveau job

+ 48 - 11
src/Commands/CronCommand.php

@@ -5,6 +5,8 @@ namespace App\Commands;
 use App\Service\Cron\CronjobInterface;
 use App\Service\Cron\UI\ConsoleUI;
 use App\Service\ServiceIterator\CronjobIterator;
+use Monolog\Formatter\LineFormatter;
+use Monolog\Handler\RotatingFileHandler;
 use Psr\Log\LoggerInterface;
 use RuntimeException;
 use Symfony\Component\Console\Attribute\AsCommand;
@@ -101,6 +103,8 @@ class CronCommand extends Command
     {
         $this->output = $output;
 
+        $this->configureLoggerFormatter();
+
         /** @var FormatterHelper $formatter */
         $formatter = $this->getHelper('formatter');
 
@@ -135,15 +139,13 @@ class CronCommand extends Command
             }
         }
 
-        $this->logger->info(
-            'CronCommand will execute ' .
-            implode(', ', array_map(static function($job) { return $job->name(); }, $jobs)) .
-            ($preview ? ' [PREVIEW MODE]' : '')
-        );
-
         $results = [];
 
         foreach ($jobs as $job) {
+            $this->logger->info(
+                'CronCommand will execute `' . $job->name() . '`' . ($preview ? ' [PREVIEW MODE]' : '')
+            );
+
             $results[] = $this->runJob($job, $preview);
         }
 
@@ -196,24 +198,59 @@ class CronCommand extends Command
         $ui = new ConsoleUI($this->output);
         $job->setUI($ui);
 
+        $this->configureLoggerFormatter($job->name());
+
         try {
             if ($preview) {
                 $job->preview();
             } else {
                 $job->execute();
             }
+
+            $t1 = microtime(true);
+
+            $msg = "Job has been successfully executed (" . round($t1 - $t0, 2) . " sec.)" . ($preview ? ' [PREVIEW MODE]' : '');
+            $this->output->writeln($formatter->formatSection($job->name(), $msg));
+            $this->logger->info($job->name() . ' - ' . $msg);
+
         } catch (Throwable $e) {
             $this->logger->critical($e);
             $this->output->write("An error happened while running the process : " . $e);
             return Command::FAILURE;
+
+        } finally {
+            $this->resetLoggerFormatter();
         }
 
-        $t1 = microtime(true);
+        return Command::SUCCESS;
+    }
 
-        $msg = "Job has been successfully executed (" . round($t1 - $t0, 2) . " sec.)" . ($preview ? ' [PREVIEW MODE]' : '');
-        $this->output->writeln($formatter->formatSection($job->name(), $msg));
-        $this->logger->info($job->name() . ' - ' . $msg);
+    /**
+     * Modify the RotatingFile logger line format to match the display the current job's name (if any)
+     *
+     * @param string|null $jobName
+     * @return void
+     */
+    protected function configureLoggerFormatter(string | null $jobName = null): void {
+        // @phpstan-ignore-next-line
+        foreach ($this->logger->getHandlers() as $handler) {
+            if ($handler instanceof RotatingFileHandler) {
 
-        return Command::SUCCESS;
+                $format = "[%datetime%] " .
+                          ($jobName !== null ? "[" . $jobName . "] " : "") .
+                          "%channel%.%level_name%: %message% %context% %extra%\n";
+
+                $handler->setFormatter(new LineFormatter($format, 'Y-m-d H:i:s.u'));
+            }
+        }
+    }
+
+    /**
+     * Alias for `$this->configureLoggerFormatter(null)`
+     * @return void
+     */
+    protected function resetLoggerFormatter(): void
+    {
+        $this->configureLoggerFormatter(null);
     }
 }