Browse Source

configure logging for dolibarr sync

Olivier Massot 3 years ago
parent
commit
7df4484dc2

+ 74 - 7
config/packages/dev/monolog.yaml

@@ -1,10 +1,81 @@
+# Voir doc/logging.md
 monolog:
     handlers:
-        main:
+        # sorties standards (stdout, stderr, console)
+        stderr:
             type: stream
-            path: "%kernel.logs_dir%/%kernel.environment%.log"
+            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: swift_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%/%kernel.environment%/%kernel.environment%.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
-            channels: ["!event"]
+            max_files: 3
+            channels: security
+
+        # logs spécifiques à certains process
+        cron:
+            type: group
+            members: [cron_file]
+        cron_file:
+            type: rotating_file
+            path: "%kernel.logs_dir%/%kernel.environment%.cron.log"
+            level: debug
+            max_files: 7
+            channels: cron
+#        cron_critical:
+#            type:           fingers_crossed
+#            action_level:   critical
+#            handler:        cron_swift
+#        cron_swift:
+#            type:           swift_mailer
+#            from_email:     "process@opentalent.fr"
+#            to_email:       "exploitation@opentalent.fr"
+#            subject:        Critical Error Occurred
+#            level:          error
+#            formatter:  monolog.formatter.html
+#            content_type: text/html
+
+        # logs spécifiques au service de synchro dolibarr
+        dolibarrsync:
+            type: rotating_file
+            path: "%kernel.logs_dir%/%kernel.environment%.dolibarrsync.log"
+            level: debug
+            max_files: 7
+            channels: dolibarrsync
+
         # uncomment to get logging in your browser
         # you may have to allow bigger header sizes in your Web server configuration
         #firephp:
@@ -13,7 +84,3 @@ monolog:
         #chromephp:
         #    type: chromephp
         #    level: info
-        console:
-            type: console
-            process_psr_3_messages: false
-            channels: ["!event", "!doctrine", "!console"]

+ 3 - 3
config/packages/prod/monolog.yaml

@@ -3,12 +3,12 @@ monolog:
         main:
             type: fingers_crossed
             action_level: error
-            handler: nested
+            handler: nested_stderr
             excluded_http_codes: [404, 405]
             buffer_size: 50 # How many messages should be saved? Prevent memory leaks
-        nested:
+        nested_stderr:
             type: stream
-            path: php://stderr
+            path: php://stderr  # Handled by the apache logging system
             level: debug
             formatter: monolog.formatter.json
         console:

+ 6 - 1
config/services.yaml

@@ -42,6 +42,11 @@ services:
     App\Service\Access\HandleOptionalsRoles:
         - !tagged_iterator app.optionalsroles
 
+
+    App\Service\Dolibarr\DolibarrSync\DolibarrSyncService:
+        tags:
+            - { name: monolog.logger, channel: dolibarrsync }
+
     #########################################
     ##  SERIALIZER Decorates ##
     App\Serializer\DefaultNormalizer:
@@ -61,4 +66,4 @@ services:
     ##  LISTENER ##
     App\EventListener\DoctrineFilter\DoctrineFilterListener:
         tags:
-            - { name: kernel.event_listener, event: kernel.request }
+            - { name: kernel.event_listener, event: kernel.request }

+ 84 - 0
doc/logging.md

@@ -0,0 +1,84 @@
+# Logging
+
+Le logging s'effectue avec monolog: <https://symfony.com/doc/5.4/logging.html>
+
+Les logs sont traités par channels (ex : security, doctrine, http...)
+On peut consulter la liste des channels actifs avec la commande :
+
+     ./bin/console debug:container monolog.log
+
+Pour enregistrer un nouveau canal, on configure le service dans `config/services.yaml`:
+
+    App\Service\MyService:
+        tags:
+            - { name: monolog.logger, channel: my_channel }
+
+
+## Canaux et traitements
+
+### Principe général
+
+Certains handlers sont communs à différents canaux : stderr, console, critical
+On se contente alors d'exclure les canaux non pertinents avec la syntaxe suivante:
+
+    channels: ["!event", "!doctrine"]
+
+
+D'autres sont plus spécifiques, comme les différents `rotating_files`. On définit un ou plusieurs canaux
+concernés :
+
+        file_main:
+            type: rotating_file
+            [...]
+            channels: ["logger", "php", "doctrine", "http_client", "elastica"]
+        file_auth:
+            type: rotating_file
+            [...]
+            channels: security
+
+Enfin, d'autres sont vraiment dédiés à des process particuliers, comme des opérations d'export ou de 
+synchronisation.
+
+
+#### stderr
+
+Tous les loggers (exceptés `event` et `event`) transmettent les messages de niveau ERROR ou plus vers la sortie 
+d'erreur stderr de php. Le stream est ensuite géré par le serveur apache, nginx ou autre.
+
+#### console
+
+La console associe automatiquement les niveaux de log avec la verbosité attendue :
+
+| LoggerInterface | Verbosity | Command line |
+| --- | --- | --- |
+| ->error() | OutputInterface::VERBOSITY_QUIET | stderr |
+| ->warning() | OutputInterface::VERBOSITY_NORMAL | stdout |
+| ->notice() | OutputInterface::VERBOSITY_VERBOSE | -v |
+| ->info() | OutputInterface::VERBOSITY_VERY_VERBOSE | -vv |
+| ->debug()  | OutputInterface::VERBOSITY_DEBUG  | -vvv |
+
+
+> Voir: https://symfony.com/doc/current/logging/monolog_console.html
+
+#### rotating_files (main, et particuliers)
+
+Les canaux natifs ou custom sont par défaut gérés par un handler de type rotating_file qui logue les messages 
+dans `var/log/{env}.main.log`
+
+Certains canaux sont gérés par un handler particulier et logués dans des fichiers spécifiques. Par ex, 
+le canal `doctrine` est redirigé vers `var/log/{env}.doctrine.log`
+
+#### critical
+
+En cas d'erreur de niveau critical ou supérieur, un handler de type finger_crossed passe les logs à un handler 
+de type `mailer` (par l'intermédiaire d'un handler `deduplicated` qui évitera les lignes en doublon).
+
+Le handler `mailer` envoie ensuite un mail à l'exploitation.
+
+
+
+
+
+
+
+

+ 8 - 4
src/Service/Dolibarr/DolibarrSync/DolibarrSyncService.php

@@ -26,6 +26,7 @@ use HttpException;
 use libphonenumber\PhoneNumber;
 use libphonenumber\PhoneNumberFormat;
 use libphonenumber\PhoneNumberUtil;
+use Monolog\Handler\RotatingFileHandler;
 use Psr\Log\LoggerInterface;
 use Symfony\Contracts\Translation\TranslatorInterface;
 
@@ -33,7 +34,7 @@ use Symfony\Contracts\Translation\TranslatorInterface;
  * Push the data from the Opentalent DB into the Dolibarr DB, trough both applications
  * REST APIs.
  *
- * ** /!\ This sync is and must stay one-sided: opentalent data => dolibarr db **
+ * ** /!\ This sync is and must remain one-sided: Opentalent DB => Dolibarr DB **
  */
 class DolibarrSyncService
 {
@@ -59,7 +60,7 @@ class DolibarrSyncService
      * @throws Exception
      */
     public function scan(): array {
-        $this->logger->info("Dolibarr sync started");
+        $this->logger->info("-- Scan started --");
 
         // Index the dolibarr clients by organization ids
         $dolibarrClientsIndex = $this->getDolibarrSocietiesIndex();
@@ -263,6 +264,7 @@ class DolibarrSyncService
             }
         }
 
+        $this->logger->info('Scan ended');
         return $operations;
     }
 
@@ -277,18 +279,20 @@ class DolibarrSyncService
      */
     public function execute(array $operations): array
     {
-        $this->logger->info('Execution started, ' . count($operations) . ' operations pending...');
+        $this->logger->info('-- Execution started --');
+        $this->logger->info(count($operations) . ' operations pending...');
         $done = 0; $errors = 0; $unknown = 0;
 
         foreach ($operations as $operation) {
             if ($operation->getStatus() !== DolibarrSyncOperation::STATUS_READY) {
                 // operation has already been treated
+                $this->logger->warning('Tried to execute an operation that was not marked as ready : ' . $operation);
                 continue;
             }
             $operation->execute();
 
             if ($operation->getStatus() === DolibarrSyncOperation::STATUS_ERROR) {
-                $this->logger->error('Error while executing : ' . $operation);
+                $this->logger->error('Error while executing operation : ' . $operation);
                 $this->logger->error($operation->getErrorMessage());
                 $errors++;
             } elseif ($operation->getStatus() === DolibarrSyncOperation::STATUS_DONE) {