1
0
Fork 0
python-docs-fr/howto/logging-cookbook.po

2699 lines
124 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Copyright (C) 2001-2018, Python Software Foundation
# For licence information, see README file.
#
msgid ""
msgstr ""
"Project-Id-Version: Python 3\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-01-23 09:57+0100\n"
"PO-Revision-Date: 2023-02-01 22:16+0100\n"
"Last-Translator: \n"
"Language-Team: FRENCH <traductions@lists.afpy.org>\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.2.1\n"
#: howto/logging-cookbook.rst:5
msgid "Logging Cookbook"
msgstr "Recettes pour la journalisation"
#: howto/logging-cookbook.rst:0
msgid "Author"
msgstr "Auteur"
#: howto/logging-cookbook.rst:7
msgid "Vinay Sajip <vinay_sajip at red-dove dot com>"
msgstr "Vinay Sajip <vinay_sajip at red-dove dot com>"
#: howto/logging-cookbook.rst:9
msgid ""
"This page contains a number of recipes related to logging, which have been "
"found useful in the past. For links to tutorial and reference information, "
"please see :ref:`cookbook-ref-links`."
msgstr ""
"Cette page contient des recettes relatives à la journalisation qui se sont "
"avérées utiles par le passé. Pour des liens vers le tutoriel et des "
"informations de référence, consultez :ref:`ces autres ressources <cookbook-"
"ref-links>`."
#: howto/logging-cookbook.rst:16
msgid "Using logging in multiple modules"
msgstr "Journalisation dans plusieurs modules"
#: howto/logging-cookbook.rst:18
msgid ""
"Multiple calls to ``logging.getLogger('someLogger')`` return a reference to "
"the same logger object. This is true not only within the same module, but "
"also across modules as long as it is in the same Python interpreter "
"process. It is true for references to the same object; additionally, "
"application code can define and configure a parent logger in one module and "
"create (but not configure) a child logger in a separate module, and all "
"logger calls to the child will pass up to the parent. Here is a main "
"module::"
msgstr ""
"Deux appels à ``logging.getLogger('unLogger')`` renvoient toujours une "
"référence vers le même objet de journalisation. Cest valable à lintérieur "
"dun module, mais aussi dans des modules différents pour autant que ce soit "
"le même processus de linterpréteur Python. En plus, le code dune "
"application peut définir et configurer une journalisation parente dans un "
"module et créer (mais pas configurer) une journalisation fille dans un "
"module séparé. Les appels à la journalisation fille passeront alors à la "
"journalisation parente. Voici un module principal ::"
#: howto/logging-cookbook.rst:56
msgid "Here is the auxiliary module::"
msgstr "Voici un module auxiliaire ::"
#: howto/logging-cookbook.rst:76
msgid "The output looks like this:"
msgstr "La sortie ressemble à ceci ::"
#: howto/logging-cookbook.rst:102
msgid "Logging from multiple threads"
msgstr "Journalisation avec des fils dexécution multiples"
#: howto/logging-cookbook.rst:104
msgid ""
"Logging from multiple threads requires no special effort. The following "
"example shows logging from the main (initial) thread and another thread::"
msgstr ""
"La journalisation avec des fils dexécution multiples ne requiert pas "
"deffort particulier. Lexemple suivant montre comment journaliser depuis le "
"fil principal (c.-à-d. initial) et un autre fil ::"
#: howto/logging-cookbook.rst:133
msgid "When run, the script should print something like the following:"
msgstr "À lexécution, le script doit afficher quelque chose comme ça ::"
#: howto/logging-cookbook.rst:155
msgid ""
"This shows the logging output interspersed as one might expect. This "
"approach works for more threads than shown here, of course."
msgstr ""
"Les entrées de journalisation sont entrelacées, comme on pouvait sy "
"attendre. Cette approche fonctionne aussi avec plus de fils que dans "
"lexemple, bien sûr."
#: howto/logging-cookbook.rst:159
msgid "Multiple handlers and formatters"
msgstr "Plusieurs gestionnaires et formateurs"
#: howto/logging-cookbook.rst:161
msgid ""
"Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has "
"no minimum or maximum quota for the number of handlers you may add. "
"Sometimes it will be beneficial for an application to log all messages of "
"all severities to a text file while simultaneously logging errors or above "
"to the console. To set this up, simply configure the appropriate handlers. "
"The logging calls in the application code will remain unchanged. Here is a "
"slight modification to the previous simple module-based configuration "
"example::"
msgstr ""
"Les gestionnaires de journalisation sont des objets Python ordinaires. La "
"méthode :meth:`~Logger.addHandler` nest pas limitée, en nombre minimum ou "
"maximum, en gestionnaires que vous pouvez ajouter. Parfois, il peut être "
"utile pour une application de journaliser tous les messages quels que soient "
"leurs niveaux vers un fichier texte, tout en journalisant les erreurs (et "
"plus grave) dans la console. Pour ce faire, configurez simplement les "
"gestionnaires de manière adéquate. Les appels de journalisation dans le code "
"de lapplication resteront les mêmes. Voici une légère modification de "
"lexemple précédent dans une configuration au niveau du module ::"
#: howto/logging-cookbook.rst:194
msgid ""
"Notice that the 'application' code does not care about multiple handlers. "
"All that changed was the addition and configuration of a new handler named "
"*fh*."
msgstr ""
"Notez que le code de « lapplication » ignore la multiplicité des "
"gestionnaires. Les modifications consistent simplement en lajout et la "
"configuration dun nouveau gestionnaire appelé *fh*."
#: howto/logging-cookbook.rst:197
msgid ""
"The ability to create new handlers with higher- or lower-severity filters "
"can be very helpful when writing and testing an application. Instead of "
"using many ``print`` statements for debugging, use ``logger.debug``: Unlike "
"the print statements, which you will have to delete or comment out later, "
"the logger.debug statements can remain intact in the source code and remain "
"dormant until you need them again. At that time, the only change that needs "
"to happen is to modify the severity level of the logger and/or handler to "
"debug."
msgstr ""
"La possibilité de créer de nouveaux gestionnaires avec des filtres sur un "
"niveau de gravité supérieur ou inférieur peut être très utile lors de "
"lécriture ou du test dune application. Au lieu dutiliser de nombreuses "
"instructions ``print`` pour le débogage, utilisez ``logger.debug`` : "
"contrairement aux instructions ``print``, que vous devrez supprimer ou "
"commenter plus tard, les instructions ``logger.debug`` peuvent demeurer "
"telles quelles dans le code source et restent dormantes jusquà ce que vous "
"en ayez à nouveau besoin. À ce moment-là, il suffit de modifier le niveau de "
"gravité de la journalisation ou du gestionnaire pour déboguer."
#: howto/logging-cookbook.rst:208
msgid "Logging to multiple destinations"
msgstr "Journalisation vers plusieurs destinations"
#: howto/logging-cookbook.rst:210
msgid ""
"Let's say you want to log to console and file with different message formats "
"and in differing circumstances. Say you want to log messages with levels of "
"DEBUG and higher to file, and those messages at level INFO and higher to the "
"console. Let's also assume that the file should contain timestamps, but the "
"console messages should not. Here's how you can achieve this::"
msgstr ""
"Supposons que vous souhaitiez journaliser dans la console et dans un fichier "
"avec différents formats de messages et avec différents critères. Supposons "
"que vous souhaitiez consigner les messages de niveau DEBUG et supérieur dans "
"le fichier, et les messages de niveau INFO et supérieur dans la console. "
"Supposons également que le fichier doive contenir des horodatages, mais pas "
"les messages de la console. Voici comment y parvenir ::"
#: howto/logging-cookbook.rst:248
msgid "When you run this, on the console you will see"
msgstr "Quand vous le lancez, vous devez voir"
#: howto/logging-cookbook.rst:257
msgid "and in the file you will see something like"
msgstr "et, dans le fichier, vous devez trouver"
#: howto/logging-cookbook.rst:267
msgid ""
"As you can see, the DEBUG message only shows up in the file. The other "
"messages are sent to both destinations."
msgstr ""
"Comme vous pouvez le constater, le message DEBUG napparaît que dans le "
"fichier. Les autres messages sont envoyés vers les deux destinations."
#: howto/logging-cookbook.rst:270
msgid ""
"This example uses console and file handlers, but you can use any number and "
"combination of handlers you choose."
msgstr ""
"Cet exemple utilise la console et des gestionnaires de fichier, mais vous "
"pouvez utiliser et combiner autant de gestionnaires que de besoin."
#: howto/logging-cookbook.rst:273
msgid ""
"Note that the above choice of log filename ``/tmp/myapp.log`` implies use of "
"a standard location for temporary files on POSIX systems. On Windows, you "
"may need to choose a different directory name for the log - just ensure that "
"the directory exists and that you have the permissions to create and update "
"files in it."
msgstr ""
"Notez que le choix du nom de fichier journal ``/tmp/myapp.log`` ci-dessus "
"implique l'utilisation d'un emplacement standard pour les fichiers "
"temporaires sur les systèmes POSIX. Sous Windows, vous devrez peut-être "
"choisir un nom de répertoire différent pour le journal assurez-vous "
"simplement que le répertoire existe et que vous disposez des autorisations "
"nécessaires pour créer et mettre à jour des fichiers dans celui-ci."
#: howto/logging-cookbook.rst:282
msgid "Custom handling of levels"
msgstr "Personnalisation du niveau de journalisation"
#: howto/logging-cookbook.rst:284
msgid ""
"Sometimes, you might want to do something slightly different from the "
"standard handling of levels in handlers, where all levels above a threshold "
"get processed by a handler. To do this, you need to use filters. Let's look "
"at a scenario where you want to arrange things as follows:"
msgstr ""
"Il peut arriver que vous souhaitiez que vos gestionnaires journalisent "
"légèrement différemment de la gestion standard des niveaux, où tous les "
"niveaux au-dessus d'un seuil sont traités par un gestionnaire. Pour ce "
"faire, vous devez utiliser des filtres. Examinons un scénario dans lequel "
"vous souhaitez organiser les choses comme suit :"
# énumération
#: howto/logging-cookbook.rst:289
msgid "Send messages of severity ``INFO`` and ``WARNING`` to ``sys.stdout``"
msgstr ""
"envoyer les messages de niveau ``INFO`` et ``WARNING`` à ``sys.stdout`` ;"
# énumération
#: howto/logging-cookbook.rst:290
msgid "Send messages of severity ``ERROR`` and above to ``sys.stderr``"
msgstr ""
"envoyer les messages de niveau ``ERROR`` et au-dessus à ``sys.stderr`` ;"
# énumération
#: howto/logging-cookbook.rst:291
msgid "Send messages of severity ``DEBUG`` and above to file ``app.log``"
msgstr ""
"envoyer les messages de niveau ``DEBUG`` et au-dessus vers le fichier ``app."
"log``."
#: howto/logging-cookbook.rst:293
msgid "Suppose you configure logging with the following JSON:"
msgstr ""
"Supposons que vous configurez la journalisation avec le contenu au format "
"JSON suivant :"
#: howto/logging-cookbook.rst:335
msgid ""
"This configuration does *almost* what we want, except that ``sys.stdout`` "
"would show messages of severity ``ERROR`` and above as well as ``INFO`` and "
"``WARNING`` messages. To prevent this, we can set up a filter which excludes "
"those messages and add it to the relevant handler. This can be configured by "
"adding a ``filters`` section parallel to ``formatters`` and ``handlers``:"
msgstr ""
"Cette configuration fait *presque* ce que nous voulons, sauf que ``sys."
"stdout`` affiche les messages de gravité ``ERROR`` et supérieurs ainsi que "
"les messages ``INFO`` et ``WARNING``. Pour éviter cela, nous pouvons "
"configurer un filtre qui exclut ces messages et l'ajouter au gestionnaire "
"approprié. Effectuons la configuration en ajoutant une section ``filters`` "
"parallèle à ``formatters`` et ``handlers`` :"
#: howto/logging-cookbook.rst:350
msgid "and changing the section on the ``stdout`` handler to add it:"
msgstr ""
"et en changeant la section du gestionnaire ``stdout`` pour ajouter le "
"filtre :"
#: howto/logging-cookbook.rst:362
msgid ""
"A filter is just a function, so we can define the ``filter_maker`` (a "
"factory function) as follows:"
msgstr ""
"Un filtre n'est qu'une fonction, nous pouvons donc définir un "
"``filter_maker`` (une fonction fabrique) comme suit :"
#: howto/logging-cookbook.rst:375
msgid ""
"This converts the string argument passed in to a numeric level, and returns "
"a function which only returns ``True`` if the level of the passed in record "
"is at or below the specified level. Note that in this example I have defined "
"the ``filter_maker`` in a test script ``main.py`` that I run from the "
"command line, so its module will be ``__main__`` - hence the ``__main__."
"filter_maker`` in the filter configuration. You will need to change that if "
"you define it in a different module."
msgstr ""
"Elle convertit la chaîne transmise en argument vers un niveau numérique puis "
"renvoie une fonction qui ne renvoie ``True`` que si le niveau de "
"l'enregistrement transmis est inférieur ou égal au niveau spécifié. Notez "
"que dans cet exemple, nous avons défini ``filter_maker`` dans un script de "
"test ``main.py`` qui est exécuté depuis la ligne de commande, donc son "
"module est ``__main__`` d'où le ``__main__.filter_maker`` dans la "
"configuration du filtre. Vous devez le changer si vous la définissez dans un "
"module différent."
#: howto/logging-cookbook.rst:383
msgid "With the filter added, we can run ``main.py``, which in full is:"
msgstr ""
"Avec le filtre, nous pouvons exécuter ``main.py`` dont voici la version "
"complète :"
#: howto/logging-cookbook.rst:453
msgid "And after running it like this:"
msgstr "Et après l'avoir exécuté comme ceci :"
#: howto/logging-cookbook.rst:459
msgid "We can see the results are as expected:"
msgstr "Nous obtenons le résultat attendu :"
#: howto/logging-cookbook.rst:485
msgid "Configuration server example"
msgstr "Exemple dun serveur de configuration"
#: howto/logging-cookbook.rst:487
msgid "Here is an example of a module using the logging configuration server::"
msgstr ""
"Voici un exemple de module mettant en œuvre la configuration de la "
"journalisation *via* un serveur ::"
#: howto/logging-cookbook.rst:518
msgid ""
"And here is a script that takes a filename and sends that file to the "
"server, properly preceded with the binary-encoded length, as the new logging "
"configuration::"
msgstr ""
"Et voici un script qui, à partir dun nom de fichier, commence par envoyer "
"la taille du fichier encodée en binaire (comme il se doit), puis envoie ce "
"fichier au serveur pour définir la nouvelle configuration de "
"journalisation ::"
#: howto/logging-cookbook.rst:543
msgid "Dealing with handlers that block"
msgstr "Utilisation de gestionnaires bloquants"
#: howto/logging-cookbook.rst:547
msgid ""
"Sometimes you have to get your logging handlers to do their work without "
"blocking the thread you're logging from. This is common in web applications, "
"though of course it also occurs in other scenarios."
msgstr ""
"Parfois, il est nécessaire que les gestionnaires de journalisation fassent "
"leur travail sans bloquer le fil dexécution qui émet des événements. Cest "
"généralement le cas dans les applications Web, mais aussi bien sûr dans "
"dautres scénarios."
#: howto/logging-cookbook.rst:551
msgid ""
"A common culprit which demonstrates sluggish behaviour is the :class:"
"`SMTPHandler`: sending emails can take a long time, for a number of reasons "
"outside the developer's control (for example, a poorly performing mail or "
"network infrastructure). But almost any network-based handler can block: "
"Even a :class:`SocketHandler` operation may do a DNS query under the hood "
"which is too slow (and this query can be deep in the socket library code, "
"below the Python layer, and outside your control)."
msgstr ""
"Un gestionnaire classiquement lent est le :class:`SMTPHandler` : lenvoi de-"
"mails peut prendre beaucoup de temps, pour un certain nombre de raisons "
"indépendantes du développeur (par exemple, une infrastructure de messagerie "
"ou de réseau peu performante). Mais nimporte quel autre gestionnaire "
"utilisant le réseau ou presque peut aussi savérer bloquant : même une "
"simple opération :class:`SocketHandler` peut faire une requête DNS implicite "
"et être ainsi très lente (cette requête peut être enfouie profondément dans "
"le code de la bibliothèque daccès réseau, sous la couche Python, et hors de "
"votre contrôle)."
#: howto/logging-cookbook.rst:559
msgid ""
"One solution is to use a two-part approach. For the first part, attach only "
"a :class:`QueueHandler` to those loggers which are accessed from performance-"
"critical threads. They simply write to their queue, which can be sized to a "
"large enough capacity or initialized with no upper bound to their size. The "
"write to the queue will typically be accepted quickly, though you will "
"probably need to catch the :exc:`queue.Full` exception as a precaution in "
"your code. If you are a library developer who has performance-critical "
"threads in their code, be sure to document this (together with a suggestion "
"to attach only ``QueueHandlers`` to your loggers) for the benefit of other "
"developers who will use your code."
msgstr ""
"Une solution consiste à utiliser une approche en deux parties. Pour la "
"première partie, affectez un seul :class:`QueueHandler` à la journalisation "
"des fils dexécution critiques pour les performances. Ils écrivent "
"simplement dans leur file dattente, qui peut être dimensionnée à une "
"capacité suffisamment grande ou initialisée sans limite supérieure en "
"taille. Lécriture dans la file dattente est généralement acceptée "
"rapidement, mais nous vous conseillons quand même de prévoir dintercepter "
"lexception :exc:`queue.Full` par précaution dans votre code. Si vous "
"développez une bibliothèque avec des fils dexécution critiques pour les "
"performances, documentez-le bien (avec une suggestion de naffecter que des "
"``QueueHandlers`` à votre journalisation) pour faciliter le travail des "
"développeurs qui utilisent votre code."
#: howto/logging-cookbook.rst:570
msgid ""
"The second part of the solution is :class:`QueueListener`, which has been "
"designed as the counterpart to :class:`QueueHandler`. A :class:"
"`QueueListener` is very simple: it's passed a queue and some handlers, and "
"it fires up an internal thread which listens to its queue for LogRecords "
"sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that "
"matter). The ``LogRecords`` are removed from the queue and passed to the "
"handlers for processing."
msgstr ""
"La deuxième partie de la solution est la classe :class:`QueueListener`, "
"conçue comme lhomologue de :class:`QueueHandler`. Un :class:`QueueListener` "
"est très simple : vous lui passez une file dattente et des gestionnaires, "
"et il lance un fil dexécution interne qui scrute la file dattente pour "
"récupérer les événements envoyés par les ``QueueHandlers`` (ou toute autre "
"source de ``LogRecords``, dailleurs). Les ``LogRecords`` sont supprimés de "
"la file dattente et transmis aux gestionnaires pour traitement."
#: howto/logging-cookbook.rst:578
msgid ""
"The advantage of having a separate :class:`QueueListener` class is that you "
"can use the same instance to service multiple ``QueueHandlers``. This is "
"more resource-friendly than, say, having threaded versions of the existing "
"handler classes, which would eat up one thread per handler for no particular "
"benefit."
msgstr ""
"Lavantage davoir une classe :class:`QueueListener` séparée est que vous "
"pouvez utiliser la même instance pour servir plusieurs ``QueueHandlers``. "
"Cela consomme moins de ressources que des instances de gestionnaires "
"réparties chacune dans un fil dexécution séparé."
#: howto/logging-cookbook.rst:583
msgid "An example of using these two classes follows (imports omitted)::"
msgstr ""
"Voici un exemple dutilisation de ces deux classes (les importations sont "
"omises) ::"
#: howto/logging-cookbook.rst:601
msgid "which, when run, will produce:"
msgstr "ce qui produit ceci à lexécution :"
# suit un :
#: howto/logging-cookbook.rst:607
msgid ""
"Although the earlier discussion wasn't specifically talking about async "
"code, but rather about slow logging handlers, it should be noted that when "
"logging from async code, network and even file handlers could lead to "
"problems (blocking the event loop) because some logging is done from :mod:"
"`asyncio` internals. It might be best, if any async code is used in an "
"application, to use the above approach for logging, so that any blocking "
"code runs only in the ``QueueListener`` thread."
msgstr ""
"bien que la discussion précédente n'aborde pas spécifiquement l'utilisation "
"de code asynchrone, mais concerne les gestionnaires de journalisation lents, "
"notez que lors de la journalisation à partir de code asynchrone, les "
"gestionnaires qui écrivent vers le réseau ou même dans des fichiers peuvent "
"entraîner des problèmes (blocage de la boucle d'événements) car une certaine "
"journalisation est faite à partir du code natif de :mod:`asyncio`. Il peut "
"être préférable, si un code asynchrone est utilisé dans une application, "
"d'utiliser l'approche ci-dessus pour la journalisation, de sorte que tout ce "
"qui utilise du code bloquant ne s'exécute que dans le thread "
"``QueueListener``."
# suit un :
#: howto/logging-cookbook.rst:615
msgid ""
"Prior to Python 3.5, the :class:`QueueListener` always passed every message "
"received from the queue to every handler it was initialized with. (This was "
"because it was assumed that level filtering was all done on the other side, "
"where the queue is filled.) From 3.5 onwards, this behaviour can be changed "
"by passing a keyword argument ``respect_handler_level=True`` to the "
"listener's constructor. When this is done, the listener compares the level "
"of each message with the handler's level, and only passes a message to a "
"handler if it's appropriate to do so."
msgstr ""
"avant Python 3.5, la classe :class:`QueueListener` passait chaque message "
"reçu de la file dattente à chaque gestionnaire avec lequel linstance avait "
"été initialisée (on supposait que le filtrage de niveau était entièrement "
"effectué de lautre côté, au niveau de lalimentation de la file dattente). "
"Depuis Python 3.5, le comportement peut être modifié en passant largument "
"par mot-clé ``respect_handler_level=True`` au constructeur. Dans ce cas, la "
"``QueueListener`` compare le niveau de chaque message avec le niveau défini "
"dans chaque gestionnaire et ne transmet le message que si cest opportun."
#: howto/logging-cookbook.rst:628
msgid "Sending and receiving logging events across a network"
msgstr "Envoi et réception dévénements de journalisation à travers le réseau"
#: howto/logging-cookbook.rst:630
msgid ""
"Let's say you want to send logging events across a network, and handle them "
"at the receiving end. A simple way of doing this is attaching a :class:"
"`SocketHandler` instance to the root logger at the sending end::"
msgstr ""
"Supposons que vous souhaitiez envoyer des événements de journalisation sur "
"un réseau et les traiter à la réception. Une façon simple de faire est "
"dattacher une instance :class:`SocketHandler` à la journalisation racine de "
"lémetteur ::"
#: howto/logging-cookbook.rst:658
msgid ""
"At the receiving end, you can set up a receiver using the :mod:"
"`socketserver` module. Here is a basic working example::"
msgstr ""
"Vous pouvez configurer le récepteur en utilisant le module :mod:"
"`socketserver`. Voici un exemple élémentaire ::"
#: howto/logging-cookbook.rst:746
msgid ""
"First run the server, and then the client. On the client side, nothing is "
"printed on the console; on the server side, you should see something like:"
msgstr ""
"Lancez dabord le serveur, puis le client. Côté client, rien ne saffiche "
"sur la console ; côté serveur, vous devez voir quelque chose comme ça :"
#: howto/logging-cookbook.rst:758
msgid ""
"Note that there are some security issues with pickle in some scenarios. If "
"these affect you, you can use an alternative serialization scheme by "
"overriding the :meth:`~handlers.SocketHandler.makePickle` method and "
"implementing your alternative there, as well as adapting the above script to "
"use your alternative serialization."
msgstr ""
"Notez que ``pickle`` introduit des problèmes de sécurité dans certains "
"scénarios. Si vous êtes concerné, vous pouvez utiliser une sérialisation "
"alternative en surchargeant la méthode :meth:`~handlers.SocketHandler."
"makePickle` par votre propre implémentation, ainsi quen adaptant le script "
"ci-dessus pour utiliser votre sérialisation."
#: howto/logging-cookbook.rst:766
msgid "Running a logging socket listener in production"
msgstr ""
"Journalisation en production à laide dun connecteur en écoute sur le réseau"
#: howto/logging-cookbook.rst:770
msgid ""
"To run a logging listener in production, you may need to use a process-"
"management tool such as `Supervisor <http://supervisord.org/>`_. `Here is a "
"Gist <socket-listener-gist_>`__ which provides the bare-bones files to run "
"the above functionality using Supervisor. It consists of the following files:"
msgstr ""
"Pour de la journalisation en production *via* un connecteur réseau en "
"écoute, il est probable que vous ayez besoin dutiliser un outil de "
"surveillance tel que `Supervisor <http://supervisord.org/>`_. Vous trouverez "
"dans ce `Gist <socket-listener-gist_>`__ des gabarits pour assurer cette "
"fonction avec *Supervisor*. Il est composé des fichiers suivants :"
#: howto/logging-cookbook.rst:777
msgid "File"
msgstr "Fichier"
#: howto/logging-cookbook.rst:777
msgid "Purpose"
msgstr "Objectif"
#: howto/logging-cookbook.rst:779
msgid ":file:`prepare.sh`"
msgstr ":file:`prepare.sh`"
#: howto/logging-cookbook.rst:779
msgid "A Bash script to prepare the environment for testing"
msgstr "Script Bash pour préparer l'environnement de test"
#: howto/logging-cookbook.rst:782
msgid ":file:`supervisor.conf`"
msgstr ":file:`supervisor.conf`"
#: howto/logging-cookbook.rst:782
msgid ""
"The Supervisor configuration file, which has entries for the listener and a "
"multi-process web application"
msgstr ""
"Fichier de configuration de *Supervisor*, avec les entrées pour le "
"connecteur en écoute et l'application web multi-processus"
#: howto/logging-cookbook.rst:786
msgid ":file:`ensure_app.sh`"
msgstr ":file:`ensure_app.sh`"
#: howto/logging-cookbook.rst:786
msgid ""
"A Bash script to ensure that Supervisor is running with the above "
"configuration"
msgstr ""
"Script Bash pour s'assurer que *Supervisor* fonctionne bien avec la "
"configuration ci-dessus"
#: howto/logging-cookbook.rst:789
msgid ":file:`log_listener.py`"
msgstr ":file:`log_listener.py`"
#: howto/logging-cookbook.rst:789
msgid ""
"The socket listener program which receives log events and records them to a "
"file"
msgstr ""
"Programme en écoute sur le réseau qui reçoit les événements de "
"journalisation et les enregistre dans un fichier"
#: howto/logging-cookbook.rst:792
msgid ":file:`main.py`"
msgstr ":file:`main.py`"
#: howto/logging-cookbook.rst:792
msgid ""
"A simple web application which performs logging via a socket connected to "
"the listener"
msgstr "Application web simple qui journalise *via* un connecteur réseau"
#: howto/logging-cookbook.rst:795
msgid ":file:`webapp.json`"
msgstr ":file:`webapp.json`"
#: howto/logging-cookbook.rst:795
msgid "A JSON configuration file for the web application"
msgstr "Fichier JSON de configuration de l'application web"
#: howto/logging-cookbook.rst:797
msgid ":file:`client.py`"
msgstr ":file:`client.py`"
#: howto/logging-cookbook.rst:797
msgid "A Python script to exercise the web application"
msgstr ""
"Script Python qui interagit avec l'application web pour effectuer des appels "
"à la journalisation"
#: howto/logging-cookbook.rst:800
msgid ""
"The web application uses `Gunicorn <https://gunicorn.org/>`_, which is a "
"popular web application server that starts multiple worker processes to "
"handle requests. This example setup shows how the workers can write to the "
"same log file without conflicting with one another --- they all go through "
"the socket listener."
msgstr ""
"L'application Web utilise `Gunicorn <https://gunicorn.org/>`_, qui est un "
"serveur d'applications Web populaire qui démarre plusieurs processus de "
"travail pour gérer les demandes. Cet exemple de configuration montre comment "
"les processus peuvent écrire dans le même fichier journal sans entrer en "
"conflit les uns avec les autres — ils passent tous par le connecteur en "
"écoute."
#: howto/logging-cookbook.rst:805
msgid "To test these files, do the following in a POSIX environment:"
msgstr ""
"Pour tester ces fichiers, suivez cette procédure dans un environnement "
"POSIX :"
#: howto/logging-cookbook.rst:807
msgid ""
"Download `the Gist <socket-listener-gist_>`__ as a ZIP archive using the :"
"guilabel:`Download ZIP` button."
msgstr ""
"Téléchargez l'archive ZIP du `Gist <socket-listener-gist_>`__ à l'aide du "
"bouton :guilabel:`Download ZIP`."
#: howto/logging-cookbook.rst:810
msgid "Unzip the above files from the archive into a scratch directory."
msgstr "Décompressez les fichiers de l'archive dans un répertoire de travail."
#: howto/logging-cookbook.rst:812
msgid ""
"In the scratch directory, run ``bash prepare.sh`` to get things ready. This "
"creates a :file:`run` subdirectory to contain Supervisor-related and log "
"files, and a :file:`venv` subdirectory to contain a virtual environment into "
"which ``bottle``, ``gunicorn`` and ``supervisor`` are installed."
msgstr ""
"Dans le répertoire de travail, exécutez le script de préparation par ``bash "
"prepare.sh``. Cela crée un sous-répertoire :file:`run` pour contenir les "
"fichiers journaux et ceux relatifs à *Supervisor*, ainsi qu'un sous-"
"répertoire :file:`venv` pour contenir un environnement virtuel dans lequel "
"``bottle``, ``gunicorn`` et ``supervisor`` sont installés."
#: howto/logging-cookbook.rst:817
msgid ""
"Run ``bash ensure_app.sh`` to ensure that Supervisor is running with the "
"above configuration."
msgstr ""
"Exécutez ``bash ensure_app.sh`` pour vous assurer que *Supervisor* s'exécute "
"avec la configuration ci-dessus."
#: howto/logging-cookbook.rst:820
msgid ""
"Run ``venv/bin/python client.py`` to exercise the web application, which "
"will lead to records being written to the log."
msgstr ""
"Exécutez ``venv/bin/python client.py`` pour tester l'application Web, ce qui "
"entraîne l'écriture d'enregistrements dans le journal."
#: howto/logging-cookbook.rst:823
msgid ""
"Inspect the log files in the :file:`run` subdirectory. You should see the "
"most recent log lines in files matching the pattern :file:`app.log*`. They "
"won't be in any particular order, since they have been handled concurrently "
"by different worker processes in a non-deterministic way."
msgstr ""
"Inspectez les fichiers journaux dans le sous-répertoire :file:`run`. Vous "
"devriez voir les lignes de journal les plus récentes dans les fichiers de "
"type :file:`app.log*`. Ils ne seront pas dans un ordre particulier, car ils "
"ont été traités par les différents processus de travail de manière non "
"déterministe."
#: howto/logging-cookbook.rst:828
msgid ""
"You can shut down the listener and the web application by running ``venv/bin/"
"supervisorctl -c supervisor.conf shutdown``."
msgstr ""
"Vous pouvez arrêter le connecteur en écoute et l'application Web en "
"exécutant ``venv/bin/supervisorctl -c supervisor.conf shutdown``."
#: howto/logging-cookbook.rst:831
msgid ""
"You may need to tweak the configuration files in the unlikely event that the "
"configured ports clash with something else in your test environment."
msgstr ""
"Vous devrez peut-être modifier les fichiers de configuration dans le cas peu "
"probable où les ports configurés entrent en conflit avec autre chose dans "
"votre environnement de test."
#: howto/logging-cookbook.rst:837
msgid "Adding contextual information to your logging output"
msgstr "Ajout dinformations contextuelles dans la journalisation"
# #no-qa
#: howto/logging-cookbook.rst:839
msgid ""
"Sometimes you want logging output to contain contextual information in "
"addition to the parameters passed to the logging call. For example, in a "
"networked application, it may be desirable to log client-specific "
"information in the log (e.g. remote client's username, or IP address). "
"Although you could use the *extra* parameter to achieve this, it's not "
"always convenient to pass the information in this way. While it might be "
"tempting to create :class:`Logger` instances on a per-connection basis, this "
"is not a good idea because these instances are not garbage collected. While "
"this is not a problem in practice, when the number of :class:`Logger` "
"instances is dependent on the level of granularity you want to use in "
"logging an application, it could be hard to manage if the number of :class:"
"`Logger` instances becomes effectively unbounded."
msgstr ""
"Dans certains cas, vous pouvez souhaiter que la journalisation contienne des "
"informations contextuelles en plus des paramètres transmis à lappel de "
"journalisation. Par exemple, dans une application réseau, il peut être "
"souhaitable de consigner des informations spécifiques au client dans le "
"journal (par exemple, le nom dutilisateur ou ladresse IP du client "
"distant). Bien que vous puissiez utiliser le paramètre *extra* pour y "
"parvenir, il nest pas toujours pratique de transmettre les informations de "
"cette manière. Il peut être aussi tentant de créer des instances :class:"
"`Logger` connexion par connexion, mais ce nest pas une bonne idée car ces "
"instances :class:`Logger` ne sont pas éliminées par le ramasse-miettes. Même "
"si ce point nest pas problématique en soi si la journalisation est "
"configurée avec plusieurs niveaux de granularité, cela peut devenir "
"difficile de gérer un nombre potentiellement illimité dinstances de :class:"
"`Logger`."
#: howto/logging-cookbook.rst:854
msgid "Using LoggerAdapters to impart contextual information"
msgstr ""
"Utilisation dadaptateurs de journalisation pour transmettre des "
"informations contextuelles"
#: howto/logging-cookbook.rst:856
msgid ""
"An easy way in which you can pass contextual information to be output along "
"with logging event information is to use the :class:`LoggerAdapter` class. "
"This class is designed to look like a :class:`Logger`, so that you can call :"
"meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, :meth:"
"`exception`, :meth:`critical` and :meth:`log`. These methods have the same "
"signatures as their counterparts in :class:`Logger`, so you can use the two "
"types of instances interchangeably."
msgstr ""
"Un moyen simple de transmettre des informations contextuelles accompagnant "
"les informations de journalisation consiste à utiliser la classe :class:"
"`LoggerAdapter`. Cette classe est conçue pour ressembler à un :class:"
"`Logger`, de sorte que vous pouvez appeler :meth:`debug`, :meth:`info`, :"
"meth:`warning`, :meth:`error`, :meth:`exception`, :meth:`critical` et :meth:"
"`log`. Ces méthodes ont les mêmes signatures que leurs homologues dans :"
"class:`Logger`, vous pouvez donc utiliser les deux types dinstances de "
"manière interchangeable."
#: howto/logging-cookbook.rst:864
msgid ""
"When you create an instance of :class:`LoggerAdapter`, you pass it a :class:"
"`Logger` instance and a dict-like object which contains your contextual "
"information. When you call one of the logging methods on an instance of :"
"class:`LoggerAdapter`, it delegates the call to the underlying instance of :"
"class:`Logger` passed to its constructor, and arranges to pass the "
"contextual information in the delegated call. Here's a snippet from the code "
"of :class:`LoggerAdapter`::"
msgstr ""
"Lorsque vous créez une instance de :class:`LoggerAdapter`, vous lui "
"transmettez une instance de :class:`Logger` et un objet dictionnaire qui "
"contient vos informations contextuelles. Lorsque vous appelez lune des "
"méthodes de journalisation sur une instance de :class:`LoggerAdapter`, elle "
"délègue lappel à linstance sous-jacente de :class:`Logger` transmise à son "
"constructeur et sarrange pour intégrer les informations contextuelles dans "
"lappel délégué. Voici un extrait du code de :class:`LoggerAdapter` ::"
#: howto/logging-cookbook.rst:880
msgid ""
"The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where "
"the contextual information is added to the logging output. It's passed the "
"message and keyword arguments of the logging call, and it passes back "
"(potentially) modified versions of these to use in the call to the "
"underlying logger. The default implementation of this method leaves the "
"message alone, but inserts an 'extra' key in the keyword argument whose "
"value is the dict-like object passed to the constructor. Of course, if you "
"had passed an 'extra' keyword argument in the call to the adapter, it will "
"be silently overwritten."
msgstr ""
"Les informations contextuelles sont ajoutées dans la méthode :meth:"
"`~LoggerAdapter.process` de :class:`LoggerAdapter`. On lui passe le message "
"et les arguments par mot-clé de lappel de journalisation, et elle en "
"renvoie des versions (potentiellement) modifiées à utiliser pour la "
"journalisation sous-jacente. Limplémentation par défaut de cette méthode "
"laisse le message seul, mais insère une clé ``extra`` dans largument par "
"mot-clé dont la valeur est lobjet dictionnaire passé au constructeur. Bien "
"sûr, si vous avez passé un argument par mot-clé ``extra`` dans lappel à "
"ladaptateur, il est écrasé silencieusement."
#: howto/logging-cookbook.rst:889
msgid ""
"The advantage of using 'extra' is that the values in the dict-like object "
"are merged into the :class:`LogRecord` instance's __dict__, allowing you to "
"use customized strings with your :class:`Formatter` instances which know "
"about the keys of the dict-like object. If you need a different method, e.g. "
"if you want to prepend or append the contextual information to the message "
"string, you just need to subclass :class:`LoggerAdapter` and override :meth:"
"`~LoggerAdapter.process` to do what you need. Here is a simple example::"
msgstr ""
"Lavantage dutiliser ``extra`` est que les valeurs de lobjet dictionnaire "
"sont fusionnées dans le ``__dict__`` de linstance :class:`LogRecord`, ce "
"qui vous permet dutiliser des chaînes personnalisées avec vos instances :"
"class:`Formatter` qui connaissent les clés de lobjet dictionnaire. Si vous "
"avez besoin dune méthode différente, par exemple si vous souhaitez ajouter "
"des informations contextuelles avant ou après la chaîne de message, il vous "
"suffit de surcharger :class:`LoggerAdapter` et de remplacer :meth:"
"`~LoggerAdapter.process` pour faire ce dont vous avez besoin. Voici un "
"exemple simple ::"
#: howto/logging-cookbook.rst:905
msgid "which you can use like this::"
msgstr "que vous pouvez utiliser comme ceci ::"
#: howto/logging-cookbook.rst:910
msgid ""
"Then any events that you log to the adapter will have the value of "
"``some_conn_id`` prepended to the log messages."
msgstr ""
"Ainsi, tout événement journalisé aura la valeur de ``some_conn_id`` insérée "
"en début de message de journalisation."
#: howto/logging-cookbook.rst:914
msgid "Using objects other than dicts to pass contextual information"
msgstr ""
"Utilisation dobjets autres que les dictionnaires pour passer des "
"informations contextuelles"
#: howto/logging-cookbook.rst:916
msgid ""
"You don't need to pass an actual dict to a :class:`LoggerAdapter` - you "
"could pass an instance of a class which implements ``__getitem__`` and "
"``__iter__`` so that it looks like a dict to logging. This would be useful "
"if you want to generate values dynamically (whereas the values in a dict "
"would be constant)."
msgstr ""
"Il nest pas obligatoire de passer un dictionnaire réel à un :class:"
"`LoggerAdapter`, vous pouvez passer une instance dune classe qui implémente "
"``__getitem__`` et ``__iter__`` pour quil ressemble à un dictionnaire du "
"point de vue de la journalisation. Cest utile si vous souhaitez générer des "
"valeurs de manière dynamique (alors que les valeurs dun dictionnaire "
"seraient constantes)."
#: howto/logging-cookbook.rst:925
msgid "Using Filters to impart contextual information"
msgstr "Utilisation de filtres pour transmettre des informations contextuelles"
#: howto/logging-cookbook.rst:927
msgid ""
"You can also add contextual information to log output using a user-defined :"
"class:`Filter`. ``Filter`` instances are allowed to modify the "
"``LogRecords`` passed to them, including adding additional attributes which "
"can then be output using a suitable format string, or if needed a custom :"
"class:`Formatter`."
msgstr ""
"Un :class:`Filter` défini par lutilisateur peut aussi ajouter des "
"informations contextuelles à la journalisation. Les instances de ``Filter`` "
"sont autorisées à modifier les ``LogRecords`` qui leur sont transmis, y "
"compris par lajout dattributs supplémentaires qui peuvent ensuite être "
"intégrés à la journalisation en utilisant une chaîne de formatage appropriée "
"ou, si nécessaire, un :class:`Formatter` personnalisé."
#: howto/logging-cookbook.rst:932
msgid ""
"For example in a web application, the request being processed (or at least, "
"the interesting parts of it) can be stored in a threadlocal (:class:"
"`threading.local`) variable, and then accessed from a ``Filter`` to add, "
"say, information from the request - say, the remote IP address and remote "
"user's username - to the ``LogRecord``, using the attribute names 'ip' and "
"'user' as in the ``LoggerAdapter`` example above. In that case, the same "
"format string can be used to get similar output to that shown above. Here's "
"an example script::"
msgstr ""
"Par exemple, dans une application Web, la requête en cours de traitement (ou "
"du moins ce quelle contient dintéressant) peut être stockée dans une "
"variable locale au fil dexécution (:class:`threading.local`), puis utilisée "
"dans un ``Filter`` pour ajouter, par exemple, des informations relatives à "
"la requête (par exemple, ladresse IP distante et le nom de lutilisateur) "
"au ``LogRecord``, en utilisant les noms dattribut ``ip`` et ``user`` comme "
"dans lexemple ``LoggerAdapter`` ci-dessus. Dans ce cas, la même chaîne de "
"formatage peut être utilisée pour obtenir une sortie similaire à celle "
"indiquée ci-dessus. Voici un exemple de script ::"
#: howto/logging-cookbook.rst:978
msgid "which, when run, produces something like:"
msgstr "qui, à lexécution, produit quelque chose comme ça ::"
#: howto/logging-cookbook.rst:996
msgid "Use of ``contextvars``"
msgstr ""
#: howto/logging-cookbook.rst:998
msgid ""
"Since Python 3.7, the :mod:`contextvars` module has provided context-local "
"storage which works for both :mod:`threading` and :mod:`asyncio` processing "
"needs. This type of storage may thus be generally preferable to thread-"
"locals. The following example shows how, in a multi-threaded environment, "
"logs can populated with contextual information such as, for example, request "
"attributes handled by web applications."
msgstr ""
#: howto/logging-cookbook.rst:1004
msgid ""
"For the purposes of illustration, say that you have different web "
"applications, each independent of the other but running in the same Python "
"process and using a library common to them. How can each of these "
"applications have their own log, where all logging messages from the library "
"(and other request processing code) are directed to the appropriate "
"application's log file, while including in the log additional contextual "
"information such as client IP, HTTP request method and client username?"
msgstr ""
#: howto/logging-cookbook.rst:1011
msgid "Let's assume that the library can be simulated by the following code:"
msgstr ""
#: howto/logging-cookbook.rst:1027
msgid ""
"We can simulate the multiple web applications by means of two simple "
"classes, ``Request`` and ``WebApp``. These simulate how real threaded web "
"applications work - each request is handled by a thread:"
msgstr ""
#: howto/logging-cookbook.rst:1171
msgid ""
"If you run the above, you should find that roughly half the requests go "
"into :file:`app1.log` and the rest into :file:`app2.log`, and the all the "
"requests are logged to :file:`app.log`. Each webapp-specific log will "
"contain only log entries for only that webapp, and the request information "
"will be displayed consistently in the log (i.e. the information in each "
"dummy request will always appear together in a log line). This is "
"illustrated by the following shell output:"
msgstr ""
#: howto/logging-cookbook.rst:1218
msgid "Imparting contextual information in handlers"
msgstr "Ajout d'informations contextuelles dans la journalisation"
#: howto/logging-cookbook.rst:1220
msgid ""
"Each :class:`~Handler` has its own chain of filters. If you want to add "
"contextual information to a :class:`LogRecord` without leaking it to other "
"handlers, you can use a filter that returns a new :class:`~LogRecord` "
"instead of modifying it in-place, as shown in the following script::"
msgstr ""
"Chaque :class:`~Handler` possède sa propre chaîne de filtres. Si vous "
"souhaitez ajouter des informations contextuelles à un :class:`LogRecord` "
"sans impacter d'autres gestionnaires, vous pouvez utiliser un filtre qui "
"renvoie un nouveau :class:`~LogRecord` au lieu de le modifier sur place, "
"comme dans le script suivant ::"
#: howto/logging-cookbook.rst:1247
msgid "Logging to a single file from multiple processes"
msgstr "Journalisation vers un fichier unique à partir de plusieurs processus"
#: howto/logging-cookbook.rst:1249
msgid ""
"Although logging is thread-safe, and logging to a single file from multiple "
"threads in a single process *is* supported, logging to a single file from "
"*multiple processes* is *not* supported, because there is no standard way to "
"serialize access to a single file across multiple processes in Python. If "
"you need to log to a single file from multiple processes, one way of doing "
"this is to have all the processes log to a :class:`~handlers.SocketHandler`, "
"and have a separate process which implements a socket server which reads "
"from the socket and logs to file. (If you prefer, you can dedicate one "
"thread in one of the existing processes to perform this function.) :ref:"
"`This section <network-logging>` documents this approach in more detail and "
"includes a working socket receiver which can be used as a starting point for "
"you to adapt in your own applications."
msgstr ""
"La journalisation est fiable avec les programmes à fils dexécution "
"multiples (*thread-safe*) : rien nempêche plusieurs fils dexécution de "
"journaliser dans le même fichier, du moment que ces fils dexécution font "
"partie du même processus. En revanche, il nexiste aucun moyen standard de "
"sérialiser laccès à un seul fichier sur plusieurs processus en Python. Si "
"vous avez besoin de vous connecter à un seul fichier à partir de plusieurs "
"processus, une façon de le faire est de faire en sorte que tous les "
"processus se connectent à un :class:`~handlers.SocketHandler`, et davoir un "
"processus séparé qui implémente un serveur qui lit à partir de ce connecteur "
"et écrit les journaux dans le fichier (si vous préférez, vous pouvez dédier "
"un fil dexécution dans lun des processus existants pour exécuter cette "
"tâche). :ref:`Cette section <network-logging>` documente cette approche plus "
"en détail et inclut un connecteur en écoute réseau fonctionnel qui peut être "
"utilisé comme point de départ pour ladapter à vos propres applications."
#: howto/logging-cookbook.rst:1262
msgid ""
"You could also write your own handler which uses the :class:"
"`~multiprocessing.Lock` class from the :mod:`multiprocessing` module to "
"serialize access to the file from your processes. The existing :class:"
"`FileHandler` and subclasses do not make use of :mod:`multiprocessing` at "
"present, though they may do so in the future. Note that at present, the :mod:"
"`multiprocessing` module does not provide working lock functionality on all "
"platforms (see https://bugs.python.org/issue3770)."
msgstr ""
"Vous pouvez également écrire votre propre gestionnaire en utilisant la "
"classe :class:`~multiprocessing.Lock` du module :mod:`multiprocessing` pour "
"sérialiser laccès au fichier depuis vos processus. Les actuels :class:"
"`FileHandler` et sous-classes nutilisent pas :mod:`multiprocessing` pour le "
"moment, même sils pourraient le faire à lavenir. Notez quà lheure "
"actuelle, le module :mod:`multiprocessing` ne fournit pas un verrouillage "
"fonctionnel pour toutes les plates-formes (voir https://bugs.python.org/"
"issue3770)."
#: howto/logging-cookbook.rst:1272
msgid ""
"Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send "
"all logging events to one of the processes in your multi-process "
"application. The following example script demonstrates how you can do this; "
"in the example a separate listener process listens for events sent by other "
"processes and logs them according to its own logging configuration. Although "
"the example only demonstrates one way of doing it (for example, you may want "
"to use a listener thread rather than a separate listener process -- the "
"implementation would be analogous) it does allow for completely different "
"logging configurations for the listener and the other processes in your "
"application, and can be used as the basis for code meeting your own specific "
"requirements::"
msgstr ""
"Autrement, vous pouvez utiliser une ``Queue`` et un :class:`QueueHandler` "
"pour envoyer tous les événements de journalisation à lun des processus de "
"votre application multi-processus. Lexemple de script suivant montre "
"comment procéder ; dans lexemple, un processus découte distinct écoute les "
"événements envoyés par les autres processus et les journalise en fonction de "
"sa propre configuration de journalisation. Bien que lexemple ne montre "
"quune seule façon de faire (par exemple, vous pouvez utiliser un fil "
"dexécution découte plutôt quun processus découte séparé "
"limplémentation serait analogue), il permet des configurations de "
"journalisation complètement différentes pour celui qui écoute ainsi que pour "
"les autres processus de votre application, et peut être utilisé comme base "
"pour répondre à vos propres exigences ::"
#: howto/logging-cookbook.rst:1388
msgid ""
"A variant of the above script keeps the logging in the main process, in a "
"separate thread::"
msgstr ""
"Une variante du script ci-dessus conserve la journalisation dans le "
"processus principal, dans un fil séparé ::"
#: howto/logging-cookbook.rst:1483
msgid ""
"This variant shows how you can e.g. apply configuration for particular "
"loggers - e.g. the ``foo`` logger has a special handler which stores all "
"events in the ``foo`` subsystem in a file ``mplog-foo.log``. This will be "
"used by the logging machinery in the main process (even though the logging "
"events are generated in the worker processes) to direct the messages to the "
"appropriate destinations."
msgstr ""
"Cette variante montre comment appliquer la configuration pour des "
"enregistreurs particuliers par exemple lenregistreur ``foo`` a un "
"gestionnaire spécial qui stocke tous les événements du sous-système ``foo`` "
"dans un fichier ``mplog-foo.log``. Cest utilisé par le mécanisme de "
"journalisation dans le processus principal (même si les événements de "
"journalisation sont générés dans les processus de travail) pour diriger les "
"messages vers les destinations appropriées."
#: howto/logging-cookbook.rst:1490
msgid "Using concurrent.futures.ProcessPoolExecutor"
msgstr "Utilisation de concurrent.futures.ProcessPoolExecutor"
#: howto/logging-cookbook.rst:1492
msgid ""
"If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start "
"your worker processes, you need to create the queue slightly differently. "
"Instead of"
msgstr ""
"Si vous souhaitez utiliser :class:`concurrent.futures.ProcessPoolExecutor` "
"pour démarrer vos processus de travail, vous devez créer la file dattente "
"légèrement différemment. À la place de"
#: howto/logging-cookbook.rst:1500
msgid "you should use"
msgstr "vous devez écrire"
#: howto/logging-cookbook.rst:1506
msgid "and you can then replace the worker creation from this::"
msgstr ""
"et vous pouvez alors remplacer la création du processus de travail telle "
"que ::"
#: howto/logging-cookbook.rst:1517
msgid "to this (remembering to first import :mod:`concurrent.futures`)::"
msgstr ""
"par celle-ci (souvenez-vous dimporter au préalable :mod:`concurrent."
"futures`) ::"
#: howto/logging-cookbook.rst:1524
msgid "Deploying Web applications using Gunicorn and uWSGI"
msgstr "Déploiement dapplications Web avec *Gunicorn* et *uWSGI*"
#: howto/logging-cookbook.rst:1526
msgid ""
"When deploying Web applications using `Gunicorn <https://gunicorn.org/>`_ or "
"`uWSGI <https://uwsgi-docs.readthedocs.io/en/latest/>`_ (or similar), "
"multiple worker processes are created to handle client requests. In such "
"environments, avoid creating file-based handlers directly in your web "
"application. Instead, use a :class:`SocketHandler` to log from the web "
"application to a listener in a separate process. This can be set up using a "
"process management tool such as Supervisor - see `Running a logging socket "
"listener in production`_ for more details."
msgstr ""
"Lors du déploiement dapplications Web qui utilisent `Gunicorn <https://"
"gunicorn.org/>`_ ou `uWSGI <https://uwsgi-docs.readthedocs.io/en/latest/>`_ "
"(ou équivalent), plusieurs processus de travail sont créés pour traiter les "
"requêtes des clients. Dans de tels environnements, évitez de créer des "
"gestionnaires à fichiers directement dans votre application Web. Au lieu de "
"cela, utilisez un :class:`SocketHandler` pour journaliser depuis "
"lapplication Web vers gestionnaire réseau à lécoute dans un processus "
"séparé. Cela peut être configuré à laide dun outil de gestion de processus "
"tel que *Supervisor* (voir `Journalisation en production à laide dun "
"connecteur en écoute sur le réseau`_ pour plus de détails)."
#: howto/logging-cookbook.rst:1536
msgid "Using file rotation"
msgstr "Utilisation du roulement de fichiers"
#: howto/logging-cookbook.rst:1541
msgid ""
"Sometimes you want to let a log file grow to a certain size, then open a new "
"file and log to that. You may want to keep a certain number of these files, "
"and when that many files have been created, rotate the files so that the "
"number of files and the size of the files both remain bounded. For this "
"usage pattern, the logging package provides a :class:`~handlers."
"RotatingFileHandler`::"
msgstr ""
"Parfois, vous souhaitez laisser un fichier de journalisation grossir jusquà "
"une certaine taille, puis ouvrir un nouveau fichier et vous y enregistrer "
"les nouveaux événements. Vous souhaitez peut-être conserver un certain "
"nombre de ces fichiers et, lorsque ce nombre de fichiers aura été créé, "
"faire rouler les fichiers afin que le nombre de fichiers et la taille des "
"fichiers restent tous deux limités. Pour ce cas dusage, :class:`~handlers."
"RotatingFileHandler` est inclus dans le paquet de journalisation ::"
#: howto/logging-cookbook.rst:1573
msgid ""
"The result should be 6 separate files, each with part of the log history for "
"the application:"
msgstr ""
"Vous devez obtenir 6 fichiers séparés, chacun contenant une partie de "
"lhistorique de journalisation de lapplication :"
#: howto/logging-cookbook.rst:1585
msgid ""
"The most current file is always :file:`logging_rotatingfile_example.out`, "
"and each time it reaches the size limit it is renamed with the suffix "
"``.1``. Each of the existing backup files is renamed to increment the suffix "
"(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased."
msgstr ""
"Le fichier de journalisation actuel est toujours :file:"
"`logging_rotatingfile_example.out`, et chaque fois quil atteint la taille "
"limite, il est renommé avec le suffixe ``.1``. Chacun des fichiers de "
"sauvegarde existants est renommé pour incrémenter le suffixe (``.1`` devient "
"``.2``, etc.) et le fichier ``.6`` est effacé."
#: howto/logging-cookbook.rst:1590
msgid ""
"Obviously this example sets the log length much too small as an extreme "
"example. You would want to set *maxBytes* to an appropriate value."
msgstr ""
"De toute évidence, la longueur du journal définie dans cet exemple est "
"beaucoup trop petite. À vous de définir *maxBytes* à une valeur appropriée."
#: howto/logging-cookbook.rst:1596
msgid "Use of alternative formatting styles"
msgstr "Utilisation dautres styles de formatage"
#: howto/logging-cookbook.rst:1598
msgid ""
"When logging was added to the Python standard library, the only way of "
"formatting messages with variable content was to use the %-formatting "
"method. Since then, Python has gained two new formatting approaches: :class:"
"`string.Template` (added in Python 2.4) and :meth:`str.format` (added in "
"Python 2.6)."
msgstr ""
"Lorsque la journalisation a été ajoutée à la bibliothèque standard Python, "
"la seule façon de formater les messages avec un contenu variable était "
"dutiliser la méthode de formatage avec « % ». Depuis, Python sest enrichi "
"de deux nouvelles méthode de formatage : :class:`string.Template` (ajouté "
"dans Python 2.4) et :meth:`str.format` (ajouté dans Python 2.6)."
#: howto/logging-cookbook.rst:1604
msgid ""
"Logging (as of 3.2) provides improved support for these two additional "
"formatting styles. The :class:`Formatter` class been enhanced to take an "
"additional, optional keyword parameter named ``style``. This defaults to "
"``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond "
"to the other two formatting styles. Backwards compatibility is maintained by "
"default (as you would expect), but by explicitly specifying a style "
"parameter, you get the ability to specify format strings which work with :"
"meth:`str.format` or :class:`string.Template`. Here's an example console "
"session to show the possibilities:"
msgstr ""
"La journalisation (à partir de la version 3.2) offre une meilleure prise en "
"charge de ces deux styles de formatage supplémentaires. La classe :class:"
"`Formatter` a été améliorée pour accepter un paramètre par mot-clé "
"facultatif supplémentaire nommé ``style``. La valeur par défaut est ``'%'``, "
"les autres valeurs possibles étant ``'{'`` et ``'$'``, qui correspondent aux "
"deux autres styles de formatage. La rétrocompatibilité est maintenue par "
"défaut (comme vous vous en doutez) mais, en spécifiant explicitement un "
"paramètre de style, vous avez la possibilité de spécifier des chaînes de "
"format qui fonctionnent avec :meth:`str.format` ou :class:`string.Template`. "
"Voici un exemple de session interactive en console pour montrer les "
"possibilités :"
#: howto/logging-cookbook.rst:1638
msgid ""
"Note that the formatting of logging messages for final output to logs is "
"completely independent of how an individual logging message is constructed. "
"That can still use %-formatting, as shown here::"
msgstr ""
"Notez que le formatage des messages de journalisation est, au final, "
"complètement indépendant de la façon dont un message de journalisation "
"individuel est construit. Vous pouvez toujours utiliser formatage *via* "
"« % », comme ici ::"
#: howto/logging-cookbook.rst:1646
msgid ""
"Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take "
"positional parameters for the actual logging message itself, with keyword "
"parameters used only for determining options for how to handle the actual "
"logging call (e.g. the ``exc_info`` keyword parameter to indicate that "
"traceback information should be logged, or the ``extra`` keyword parameter "
"to indicate additional contextual information to be added to the log). So "
"you cannot directly make logging calls using :meth:`str.format` or :class:"
"`string.Template` syntax, because internally the logging package uses %-"
"formatting to merge the format string and the variable arguments. There "
"would be no changing this while preserving backward compatibility, since all "
"logging calls which are out there in existing code will be using %-format "
"strings."
msgstr ""
"Les appels de journalisation (``logger.debug()``, ``logger.info()`` etc.) ne "
"prennent que des paramètres positionnels pour le message de journalisation "
"lui-même, les paramètres par mots-clés étant utilisés uniquement pour "
"déterminer comment gérer le message réel (par exemple, le paramètre par mot-"
"clé ``exc_info`` indique que les informations de trace doivent être "
"enregistrées, ou le paramètre par mot-clé ``extra`` indique des informations "
"contextuelles supplémentaires à ajouter au journal). Vous ne pouvez donc pas "
"inclure dans les appels de journalisation à laide de la syntaxe :meth:`str."
"format` ou :class:`string.Template`, car le paquet de journalisation utilise "
"le formatage via « % » en interne pour fusionner la chaîne de format et les "
"arguments de variables. Il nest pas possible de changer ça tout en "
"préservant la rétrocompatibilité puisque tous les appels de journalisation "
"dans le code pré-existant utilisent des chaînes au format « % »."
#: howto/logging-cookbook.rst:1659
msgid ""
"There is, however, a way that you can use {}- and $- formatting to construct "
"your individual log messages. Recall that for a message you can use an "
"arbitrary object as a message format string, and that the logging package "
"will call ``str()`` on that object to get the actual format string. Consider "
"the following two classes::"
msgstr ""
"Il existe cependant un moyen dutiliser le formatage *via* « {} » et « $ » "
"pour vos messages de journalisation. Rappelez-vous que, pour un message, "
"vous pouvez utiliser un objet arbitraire comme chaîne de format de message, "
"et que le package de journalisation appelle ``str()`` sur cet objet pour "
"fabriquer la chaîne finale. Considérez les deux classes suivantes ::"
#: howto/logging-cookbook.rst:1683
msgid ""
"Either of these can be used in place of a format string, to allow {}- or $-"
"formatting to be used to build the actual \"message\" part which appears in "
"the formatted log output in place of \"%(message)s\" or \"{message}\" or "
"\"$message\". It's a little unwieldy to use the class names whenever you "
"want to log something, but it's quite palatable if you use an alias such as "
"__ (double underscore --- not to be confused with _, the single underscore "
"used as a synonym/alias for :func:`gettext.gettext` or its brethren)."
msgstr ""
"Lune ou lautre peut être utilisée à la place dune chaîne de format "
"\"%(message)s\" ou \"{message}\" ou \"$message\", afin de mettre en forme "
"*via* « { } » ou « $ » la partie « message réel » qui apparaît dans la "
"sortie de journal formatée. Il est un peu lourd dutiliser les noms de "
"classe chaque fois que vous voulez journaliser quelque chose, mais ça "
"devient acceptable si vous utilisez un alias tel que __ (double trait de "
"soulignement — à ne pas confondre avec _, le trait de soulignement unique "
"utilisé comme alias pour :func:`gettext.gettext` ou ses homologues)."
#: howto/logging-cookbook.rst:1691
msgid ""
"The above classes are not included in Python, though they're easy enough to "
"copy and paste into your own code. They can be used as follows (assuming "
"that they're declared in a module called ``wherever``):"
msgstr ""
"Les classes ci-dessus ne sont pas incluses dans Python, bien quelles soient "
"assez faciles à copier et coller dans votre propre code. Elles peuvent être "
"utilisées comme suit (en supposant quelles soient déclarées dans un module "
"appelé ``wherever``) :"
#: howto/logging-cookbook.rst:1713
msgid ""
"While the above examples use ``print()`` to show how the formatting works, "
"you would of course use ``logger.debug()`` or similar to actually log using "
"this approach."
msgstr ""
"Alors que les exemples ci-dessus utilisent ``print()`` pour montrer comment "
"fonctionne le formatage, utilisez bien sûr ``logger.debug()`` ou similaire "
"pour journaliser avec cette approche."
#: howto/logging-cookbook.rst:1717
msgid ""
"One thing to note is that you pay no significant performance penalty with "
"this approach: the actual formatting happens not when you make the logging "
"call, but when (and if) the logged message is actually about to be output to "
"a log by a handler. So the only slightly unusual thing which might trip you "
"up is that the parentheses go around the format string and the arguments, "
"not just the format string. That's because the __ notation is just syntax "
"sugar for a constructor call to one of the XXXMessage classes."
msgstr ""
"Une chose à noter est quil ny a pas de perte de performance significative "
"avec cette approche : le formatage réel ne se produit pas lorsque vous "
"effectuez lappel de journalisation, mais lorsque (et si) le message "
"journalisé est réellement sur le point dêtre écrit dans un journal par un "
"gestionnaire. Ainsi, la seule chose légèrement inhabituelle qui pourrait "
"vous perturber est que les parenthèses entourent la chaîne de format et les "
"arguments, pas seulement la chaîne de format. Cest parce que la notation __ "
"nest que du sucre syntaxique pour un appel de constructeur à lune des "
"classes ``XXXMessage``."
#: howto/logging-cookbook.rst:1725
msgid ""
"If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar "
"effect to the above, as in the following example::"
msgstr ""
"Si vous préférez, vous pouvez utiliser un :class:`LoggerAdapter` pour "
"obtenir un effet similaire à ce qui précède, comme dans lexemple suivant ::"
#: howto/logging-cookbook.rst:1756
msgid ""
"The above script should log the message ``Hello, world!`` when run with "
"Python 3.2 or later."
msgstr ""
"Le script ci-dessus journalise le message ``Hello, world!`` quand il est "
"lancé avec Python 3.2 ou ultérieur."
#: howto/logging-cookbook.rst:1765
msgid "Customizing ``LogRecord``"
msgstr "Personnalisation de ``LogRecord``"
#: howto/logging-cookbook.rst:1767
msgid ""
"Every logging event is represented by a :class:`LogRecord` instance. When an "
"event is logged and not filtered out by a logger's level, a :class:"
"`LogRecord` is created, populated with information about the event and then "
"passed to the handlers for that logger (and its ancestors, up to and "
"including the logger where further propagation up the hierarchy is "
"disabled). Before Python 3.2, there were only two places where this creation "
"was done:"
msgstr ""
"Chaque événement de journalisation est représenté par une instance :class:"
"`LogRecord`. Lorsquun événement est enregistré et non filtré en raison du "
"niveau dun enregistreur, un :class:`LogRecord` est créé, rempli avec les "
"informations de lévénement, puis transmis aux gestionnaires de cet "
"enregistreur (et ses ancêtres, jusquà et y compris lenregistreur où la "
"propagation vers le haut de la hiérarchie est désactivée). Avant Python 3.2, "
"il ny avait que deux endroits où cette création était effectuée :"
#: howto/logging-cookbook.rst:1774
msgid ""
":meth:`Logger.makeRecord`, which is called in the normal process of logging "
"an event. This invoked :class:`LogRecord` directly to create an instance."
msgstr ""
":meth:`Logger.makeRecord`, qui est appelée dans le processus normal de "
"journalisation dun événement. Elle appelait :class:`LogRecord` directement "
"pour créer une instance."
#: howto/logging-cookbook.rst:1777
msgid ""
":func:`makeLogRecord`, which is called with a dictionary containing "
"attributes to be added to the LogRecord. This is typically invoked when a "
"suitable dictionary has been received over the network (e.g. in pickle form "
"via a :class:`~handlers.SocketHandler`, or in JSON form via an :class:"
"`~handlers.HTTPHandler`)."
msgstr ""
":func:`makeLogRecord`, qui est appelée avec un dictionnaire contenant des "
"attributs à ajouter au *LogRecord*. Elle est généralement invoquée lorsquun "
"dictionnaire approprié a été reçu par le réseau (par exemple, sous forme de "
"*pickle* *via* un :class:`~handlers.SocketHandler`, ou sous format JSON "
"*via* un :class:`~handlers.HTTPHandler`)."
#: howto/logging-cookbook.rst:1783
msgid ""
"This has usually meant that if you need to do anything special with a :class:"
"`LogRecord`, you've had to do one of the following."
msgstr ""
"Cela signifiait généralement que, si vous deviez faire quelque chose de "
"spécial avec un :class:`LogRecord`, vous deviez faire lune des choses "
"suivantes."
#: howto/logging-cookbook.rst:1786
msgid ""
"Create your own :class:`Logger` subclass, which overrides :meth:`Logger."
"makeRecord`, and set it using :func:`~logging.setLoggerClass` before any "
"loggers that you care about are instantiated."
msgstr ""
"Créer votre propre sous-classe :class:`Logger`, surchargeant :meth:`Logger."
"makeRecord`, et la personnaliser à laide de :func:`~logging.setLoggerClass` "
"avant que les enregistreurs qui vous intéressaient ne soient instanciés."
#: howto/logging-cookbook.rst:1789
msgid ""
"Add a :class:`Filter` to a logger or handler, which does the necessary "
"special manipulation you need when its :meth:`~Filter.filter` method is "
"called."
msgstr ""
"Ajouter un :class:`Filter` à un enregistreur ou un gestionnaire, qui "
"effectuait la manipulation spéciale nécessaire dont vous aviez besoin "
"lorsque sa méthode :meth:`~Filter.filter` était appelée."
#: howto/logging-cookbook.rst:1793
msgid ""
"The first approach would be a little unwieldy in the scenario where (say) "
"several different libraries wanted to do different things. Each would "
"attempt to set its own :class:`Logger` subclass, and the one which did this "
"last would win."
msgstr ""
"La première approche est un peu lourde dans le scénario où (disons) "
"plusieurs bibliothèques différentes veulent faire des choses différentes. "
"Chacun essaie de définir sa propre sous-classe :class:`Logger`, et celui qui "
"la fait en dernier gagne."
#: howto/logging-cookbook.rst:1798
msgid ""
"The second approach works reasonably well for many cases, but does not allow "
"you to e.g. use a specialized subclass of :class:`LogRecord`. Library "
"developers can set a suitable filter on their loggers, but they would have "
"to remember to do this every time they introduced a new logger (which they "
"would do simply by adding new packages or modules and doing ::"
msgstr ""
"La seconde approche fonctionne raisonnablement bien dans de nombreux cas, "
"mais ne vous permet pas, par exemple, dutiliser une sous-classe spécialisée "
"de :class:`LogRecord`. Les développeurs de bibliothèques peuvent définir un "
"filtre approprié sur leurs enregistreurs, mais ils doivent se rappeler de le "
"faire chaque fois quils introduisent un nouvel enregistreur (ce quils font "
"simplement en ajoutant de nouveaux paquets ou modules et en écrivant ::"
#: howto/logging-cookbook.rst:1806
msgid ""
"at module level). It's probably one too many things to think about. "
"Developers could also add the filter to a :class:`~logging.NullHandler` "
"attached to their top-level logger, but this would not be invoked if an "
"application developer attached a handler to a lower-level library logger --- "
"so output from that handler would not reflect the intentions of the library "
"developer."
msgstr ""
"au niveau des modules). Cest probablement trop de choses auxquelles penser. "
"Les développeurs pourraient également ajouter le filtre à un :class:"
"`~logging.NullHandler` attaché à leur enregistreur de niveau supérieur, mais "
"cela ne serait pas invoqué si un développeur dapplication attachait un "
"gestionnaire à un enregistreur de bibliothèque de niveau inférieur — donc la "
"sortie de ce gestionnaire ne refléterait pas les intentions du développeur "
"de la bibliothèque."
#: howto/logging-cookbook.rst:1812
msgid ""
"In Python 3.2 and later, :class:`~logging.LogRecord` creation is done "
"through a factory, which you can specify. The factory is just a callable you "
"can set with :func:`~logging.setLogRecordFactory`, and interrogate with :"
"func:`~logging.getLogRecordFactory`. The factory is invoked with the same "
"signature as the :class:`~logging.LogRecord` constructor, as :class:"
"`LogRecord` is the default setting for the factory."
msgstr ""
"Dans Python 3.2 et ultérieurs, la création de :class:`~logging.LogRecord` "
"est effectuée via une fabrique, que vous pouvez spécifier. La fabrique est "
"juste un appelable que vous pouvez définir avec :func:`~logging."
"setLogRecordFactory`, et interroger avec :func:`~logging."
"getLogRecordFactory`. La fabrique est invoquée avec la même signature que le "
"constructeur :class:`~logging.LogRecord`, car :class:`LogRecord` est le "
"paramètre par défaut de la fabrique."
#: howto/logging-cookbook.rst:1819
msgid ""
"This approach allows a custom factory to control all aspects of LogRecord "
"creation. For example, you could return a subclass, or just add some "
"additional attributes to the record once created, using a pattern similar to "
"this::"
msgstr ""
"Cette approche permet à une fabrique personnalisée de contrôler tous les "
"aspects de la création dun *LogRecord*. Par exemple, vous pouvez renvoyer "
"une sous-classe ou simplement ajouter des attributs supplémentaires à "
"lenregistrement une fois créé, en utilisant un modèle similaire à celui-"
"ci ::"
#: howto/logging-cookbook.rst:1832
msgid ""
"This pattern allows different libraries to chain factories together, and as "
"long as they don't overwrite each other's attributes or unintentionally "
"overwrite the attributes provided as standard, there should be no surprises. "
"However, it should be borne in mind that each link in the chain adds run-"
"time overhead to all logging operations, and the technique should only be "
"used when the use of a :class:`Filter` does not provide the desired result."
msgstr ""
"Ce modèle permet à différentes bibliothèques denchaîner des fabriques, et "
"tant quelles nécrasent pas les attributs des autres ou nécrasent pas "
"involontairement les attributs fournis en standard, il ne devrait pas y "
"avoir de surprise. Cependant, il faut garder à lesprit que chaque maillon "
"de la chaîne ajoute une surcharge dexécution à toutes les opérations de "
"journalisation, et la technique ne doit être utilisée que lorsque "
"lutilisation dun :class:`Filter` ne permet pas dobtenir le résultat "
"souhaité."
#: howto/logging-cookbook.rst:1843
msgid "Subclassing QueueHandler - a ZeroMQ example"
msgstr "Dérivation de *QueueHandler* un exemple de *ZeroMQ*"
#: howto/logging-cookbook.rst:1845
msgid ""
"You can use a :class:`QueueHandler` subclass to send messages to other kinds "
"of queues, for example a ZeroMQ 'publish' socket. In the example below,the "
"socket is created separately and passed to the handler (as its 'queue')::"
msgstr ""
"Vous pouvez utiliser une sous-classe :class:`QueueHandler` pour envoyer des "
"messages à dautres types de files dattente, par exemple un connecteur "
"*ZeroMQ publish*. Dans lexemple ci-dessous, le connecteur est créé "
"séparément et transmis au gestionnaire (en tant que file dattente) ::"
#: howto/logging-cookbook.rst:1864
msgid ""
"Of course there are other ways of organizing this, for example passing in "
"the data needed by the handler to create the socket::"
msgstr ""
"Bien sûr, il existe dautres manières de faire, par exemple en transmettant "
"les données nécessaires au gestionnaire pour créer le connecteur ::"
#: howto/logging-cookbook.rst:1882
msgid "Subclassing QueueListener - a ZeroMQ example"
msgstr "Dérivation de *QueueListener* un exemple de *ZeroMQ*"
#: howto/logging-cookbook.rst:1884
msgid ""
"You can also subclass :class:`QueueListener` to get messages from other "
"kinds of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::"
msgstr ""
"Vous pouvez également dériver :class:`QueueListener` pour obtenir des "
"messages dautres types de files dattente, par exemple un connecteur "
"*ZeroMQ subscribe*. Voici un exemple ::"
#: howto/logging-cookbook.rst:1903 howto/logging-cookbook.rst:3944
msgid "Module :mod:`logging`"
msgstr "Module :mod:`logging`"
#: howto/logging-cookbook.rst:1903 howto/logging-cookbook.rst:3944
msgid "API reference for the logging module."
msgstr "Référence de lAPI du module de journalisation."
#: howto/logging-cookbook.rst:1906 howto/logging-cookbook.rst:3947
msgid "Module :mod:`logging.config`"
msgstr "Module :mod:`logging.config`"
#: howto/logging-cookbook.rst:1906 howto/logging-cookbook.rst:3947
msgid "Configuration API for the logging module."
msgstr "API pour la configuration du module de journalisation."
#: howto/logging-cookbook.rst:1909 howto/logging-cookbook.rst:3950
msgid "Module :mod:`logging.handlers`"
msgstr "Module :mod:`logging.handlers`"
#: howto/logging-cookbook.rst:1909 howto/logging-cookbook.rst:3950
msgid "Useful handlers included with the logging module."
msgstr "Gestionnaires utiles inclus avec le module de journalisation."
#: howto/logging-cookbook.rst:1911
msgid ":ref:`A basic logging tutorial <logging-basic-tutorial>`"
msgstr ""
":ref:`Les bases de lutilisation du module de journalisation <logging-basic-"
"tutorial>`"
#: howto/logging-cookbook.rst:1913
msgid ":ref:`A more advanced logging tutorial <logging-advanced-tutorial>`"
msgstr ""
":ref:`Utilisation avancée du module de journalisation <logging-advanced-"
"tutorial>`"
#: howto/logging-cookbook.rst:1917
msgid "An example dictionary-based configuration"
msgstr "Exemple de configuration basée sur un dictionnaire"
#: howto/logging-cookbook.rst:1919
msgid ""
"Below is an example of a logging configuration dictionary - it's taken from "
"the `documentation on the Django project <https://docs.djangoproject.com/en/"
"stable/topics/logging/#configuring-logging>`_. This dictionary is passed to :"
"func:`~config.dictConfig` to put the configuration into effect::"
msgstr ""
"Vous trouverez ci-dessous un exemple de dictionnaire de configuration de "
"journalisation ­ il est tiré de la `documentation du projet Django <https://"
"docs.djangoproject.com/fr/stable/topics/logging/#configuring-logging>`_. Ce "
"dictionnaire est passé à :func:`~config.dictConfig` pour activer la "
"configuration ::"
#: howto/logging-cookbook.rst:1975
msgid ""
"For more information about this configuration, you can see the `relevant "
"section <https://docs.djangoproject.com/en/stable/topics/logging/"
"#configuring-logging>`_ of the Django documentation."
msgstr ""
"Pour plus dinformations sur cette configuration, vous pouvez consulter la "
"`section correspondante <https://docs.djangoproject.com/fr/stable/topics/"
"logging/#configuring-logging>`_ de la documentation de *Django*."
#: howto/logging-cookbook.rst:1982
msgid "Using a rotator and namer to customize log rotation processing"
msgstr ""
"Utilisation dun rotateur et dun nom pour personnaliser la rotation des "
"journaux"
#: howto/logging-cookbook.rst:1984
msgid ""
"An example of how you can define a namer and rotator is given in the "
"following runnable script, which shows gzip compression of the log file::"
msgstr ""
"Lextrait de code suivant fournit un exemple de la façon dont vous pouvez "
"définir un nom et un rotateur, avec la compression par *zlib* du journal ::"
#: howto/logging-cookbook.rst:2015
msgid ""
"After running this, you will see six new files, five of which are compressed:"
msgstr ""
"Après l'avoir exécuté, vous verrez six nouveaux fichiers, dont cinq sont "
"compressés :"
#: howto/logging-cookbook.rst:2028
msgid "A more elaborate multiprocessing example"
msgstr "Exemple plus élaboré avec traitement en parallèle"
#: howto/logging-cookbook.rst:2030
msgid ""
"The following working example shows how logging can be used with "
"multiprocessing using configuration files. The configurations are fairly "
"simple, but serve to illustrate how more complex ones could be implemented "
"in a real multiprocessing scenario."
msgstr ""
"Lexemple suivant que nous allons étudier montre comment la journalisation "
"peut être utilisée, à laide de fichiers de configuration, pour un programme "
"effectuant des traitements parallèles. Les configurations sont assez "
"simples, mais servent à illustrer comment des configurations plus complexes "
"pourraient être implémentées dans un scénario multi-processus réel."
#: howto/logging-cookbook.rst:2014
msgid ""
"In the example, the main process spawns a listener process and some worker "
"processes. Each of the main process, the listener and the workers have three "
"separate configurations (the workers all share the same configuration). We "
"can see logging in the main process, how the workers log to a QueueHandler "
"and how the listener implements a QueueListener and a more complex logging "
"configuration, and arranges to dispatch events received via the queue to the "
"handlers specified in the configuration. Note that these configurations are "
"purely illustrative, but you should be able to adapt this example to your "
"own scenario."
msgstr ""
"Dans lexemple, le processus principal génère un processus découte et des "
"processus de travail. Chacun des processus, le principal, lauditeur "
"(*listener_process* dans lexemple) et les processus de travail "
"(*worker_process* dans lexemple) ont trois configurations distinctes (les "
"processus de travail partagent tous la même configuration). Nous pouvons "
"voir la journalisation dans le processus principal, comment les processus de "
"travail se connectent à un *QueueHandler* et comment lauditeur implémente "
"un *QueueListener* avec une configuration de journalisation plus complexe, "
"et sarrange pour envoyer les événements reçus *via* la file dattente aux "
"gestionnaires spécifiés dans la configuration. Notez que ces configurations "
"sont purement illustratives, mais vous devriez pouvoir adapter cet exemple à "
"votre propre scénario."
#: howto/logging-cookbook.rst:2045
msgid ""
"Here's the script - the docstrings and the comments hopefully explain how it "
"works::"
msgstr ""
"Voici le script les chaines de documentation et les commentaires "
"expliquent (en anglais), le principe de fonctionnement ::"
#: howto/logging-cookbook.rst:2257
msgid "Inserting a BOM into messages sent to a SysLogHandler"
msgstr "Insertion dune *BOM* dans les messages envoyés à un *SysLogHandler*"
#: howto/logging-cookbook.rst:2259
msgid ""
":rfc:`5424` requires that a Unicode message be sent to a syslog daemon as a "
"set of bytes which have the following structure: an optional pure-ASCII "
"component, followed by a UTF-8 Byte Order Mark (BOM), followed by Unicode "
"encoded using UTF-8. (See the :rfc:`relevant section of the specification "
"<5424#section-6>`.)"
msgstr ""
"La :rfc:`5424` requiert quun message Unicode soit envoyé à un démon "
"*syslog* sous la forme dun ensemble doctets ayant la structure suivante : "
"un composant ASCII pur facultatif, suivi dune marque dordre doctet (*BOM* "
"pour *Byte Order Mark* en anglais) UTF-8, suivie de contenu Unicode UTF-8 "
"(voir la :rfc:`la spécification correspondante <5424#section-6>`)."
#: howto/logging-cookbook.rst:2265
msgid ""
"In Python 3.1, code was added to :class:`~logging.handlers.SysLogHandler` to "
"insert a BOM into the message, but unfortunately, it was implemented "
"incorrectly, with the BOM appearing at the beginning of the message and "
"hence not allowing any pure-ASCII component to appear before it."
msgstr ""
"Dans Python 3.1, du code a été ajouté à :class:`~logging.handlers."
"SysLogHandler` pour insérer une *BOM* dans le message mais, malheureusement, "
"il a été implémenté de manière incorrecte, la *BOM* apparaissant au début du "
"message et nautorisant donc aucun composant ASCII pur à être placé devant."
#: howto/logging-cookbook.rst:2271
msgid ""
"As this behaviour is broken, the incorrect BOM insertion code is being "
"removed from Python 3.2.4 and later. However, it is not being replaced, and "
"if you want to produce :rfc:`5424`-compliant messages which include a BOM, "
"an optional pure-ASCII sequence before it and arbitrary Unicode after it, "
"encoded using UTF-8, then you need to do the following:"
msgstr ""
"Comme ce comportement est inadéquat, le code incorrect dinsertion de la "
"*BOM* a été supprimé de Python 3.2.4 et ultérieurs. Cependant, il nest pas "
"remplacé et, si vous voulez produire des messages conformes :rfc:`5424` qui "
"incluent une *BOM*, une séquence facultative en ASCII pur avant et un "
"Unicode arbitraire après, encodé en UTF-8, alors vous devez appliquer ce qui "
"suit :"
#: howto/logging-cookbook.rst:2277
msgid ""
"Attach a :class:`~logging.Formatter` instance to your :class:`~logging."
"handlers.SysLogHandler` instance, with a format string such as::"
msgstr ""
"Adjoignez une instance :class:`~logging.Formatter` à votre instance :class:"
"`~logging.handlers.SysLogHandler`, avec une chaîne de format telle que ::"
#: howto/logging-cookbook.rst:2283
msgid ""
"The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as "
"a UTF-8 BOM -- the byte-string ``b'\\xef\\xbb\\xbf'``."
msgstr ""
"Le point de code Unicode U+FEFF, lorsquil est encodé en UTF-8, est encodé "
"comme une *BOM* UTF-8 la chaîne doctets ``b'\\xef\\xbb\\xbf'``."
#: howto/logging-cookbook.rst:2286
msgid ""
"Replace the ASCII section with whatever placeholders you like, but make sure "
"that the data that appears in there after substitution is always ASCII (that "
"way, it will remain unchanged after UTF-8 encoding)."
msgstr ""
"Remplacez la section ASCII par les caractères de votre choix, mais assurez-"
"vous que les données qui y apparaissent après la substitution sont toujours "
"ASCII (ainsi elles resteront inchangées après lencodage UTF-8)."
#: howto/logging-cookbook.rst:2290
msgid ""
"Replace the Unicode section with whatever placeholders you like; if the data "
"which appears there after substitution contains characters outside the ASCII "
"range, that's fine -- it will be encoded using UTF-8."
msgstr ""
"Remplacez la section Unicode par le contenu de votre choix ; si les données "
"qui y apparaissent après la substitution contiennent des caractères en "
"dehors de la plage ASCII, cest pris en charge elles seront encodées en "
"UTF-8."
#: howto/logging-cookbook.rst:2294
msgid ""
"The formatted message *will* be encoded using UTF-8 encoding by "
"``SysLogHandler``. If you follow the above rules, you should be able to "
"produce :rfc:`5424`-compliant messages. If you don't, logging may not "
"complain, but your messages will not be RFC 5424-compliant, and your syslog "
"daemon may complain."
msgstr ""
"Le message formaté *sera* encodé en UTF-8 par ``SysLogHandler``. Si vous "
"suivez les règles ci-dessus, vous devriez pouvoir produire des messages "
"conformes à la :rfc:`5424`. Si vous ne le faites pas, la journalisation ne "
"se plaindra peut-être pas, mais vos messages ne seront pas conformes à la "
"RFC 5424 et votre démon *syslog* est susceptible de se plaindre."
#: howto/logging-cookbook.rst:2301
msgid "Implementing structured logging"
msgstr "Journalisation structurée"
#: howto/logging-cookbook.rst:2303
msgid ""
"Although most logging messages are intended for reading by humans, and thus "
"not readily machine-parseable, there might be circumstances where you want "
"to output messages in a structured format which *is* capable of being parsed "
"by a program (without needing complex regular expressions to parse the log "
"message). This is straightforward to achieve using the logging package. "
"There are a number of ways in which this could be achieved, but the "
"following is a simple approach which uses JSON to serialise the event in a "
"machine-parseable manner::"
msgstr ""
"Bien que la plupart des messages de journalisation soient destinés à être "
"lus par des humains, et donc difficilement analysables par la machine, il "
"peut arriver que vous souhaitiez produire des messages dans un format "
"structuré dans le but dêtre analysé par un programme (sans avoir besoin "
"dexpressions régulières complexes pour analyser le message du journal). "
"Cest simple à réaliser en utilisant le paquet de journalisation. Il existe "
"plusieurs façons dy parvenir et voici une approche simple qui utilise JSON "
"pour sérialiser lévénement de manière à être analysable par une machine ::"
#: howto/logging-cookbook.rst:2327
msgid "If the above script is run, it prints:"
msgstr "Si vous lancez le script ci-dessus, il imprime :"
#: howto/logging-cookbook.rst:2333 howto/logging-cookbook.rst:2375
msgid ""
"Note that the order of items might be different according to the version of "
"Python used."
msgstr ""
"Notez que lordre des éléments peut être différent en fonction de la version "
"de Python utilisée."
#: howto/logging-cookbook.rst:2336
msgid ""
"If you need more specialised processing, you can use a custom JSON encoder, "
"as in the following complete example::"
msgstr ""
"Si vous avez besoin dun traitement plus spécifique, vous pouvez utiliser un "
"encodeur JSON personnalisé, comme dans lexemple complet suivant ::"
#: howto/logging-cookbook.rst:2369
msgid "When the above script is run, it prints:"
msgstr "Quand vous exécutez le script ci-dessus, il imprime :"
#: howto/logging-cookbook.rst:2384
msgid "Customizing handlers with :func:`dictConfig`"
msgstr "Personnalisation des gestionnaires avec :func:`dictConfig`"
#: howto/logging-cookbook.rst:2386
msgid ""
"There are times when you want to customize logging handlers in particular "
"ways, and if you use :func:`dictConfig` you may be able to do this without "
"subclassing. As an example, consider that you may want to set the ownership "
"of a log file. On POSIX, this is easily done using :func:`shutil.chown`, but "
"the file handlers in the stdlib don't offer built-in support. You can "
"customize handler creation using a plain function such as::"
msgstr ""
"Il arrive de souhaiter personnaliser les gestionnaires de journalisation "
"dune manière particulière et, en utilisant :func:`dictConfig`, vous pourrez "
"peut-être le faire sans avoir à dériver les classes mères. Par exemple, "
"supposons que vous souhaitiez définir le propriétaire dun fichier journal. "
"Dans un environnement POSIX, cela se fait facilement en utilisant :func:"
"`shutil.chown`, mais les gestionnaires de fichiers de la bibliothèque "
"standard noffrent pas cette gestion nativement. Vous pouvez personnaliser "
"la création du gestionnaire à laide dune fonction simple telle que ::"
#: howto/logging-cookbook.rst:2400
msgid ""
"You can then specify, in a logging configuration passed to :func:"
"`dictConfig`, that a logging handler be created by calling this function::"
msgstr ""
"Vous pouvez ensuite spécifier, dans une configuration de journalisation "
"transmise à :func:`dictConfig`, quun gestionnaire de journalisation soit "
"créé en appelant cette fonction ::"
#: howto/logging-cookbook.rst:2433
msgid ""
"In this example I am setting the ownership using the ``pulse`` user and "
"group, just for the purposes of illustration. Putting it together into a "
"working script, ``chowntest.py``::"
msgstr ""
"Dans cet exemple, nous définissons le propriétaire à lutilisateur et au "
"groupe ``pulse``, uniquement à des fins dillustration. Rassemblons le tout "
"dans un script ``chowntest.py`` ::"
#: howto/logging-cookbook.rst:2480
msgid "To run this, you will probably need to run as ``root``:"
msgstr ""
"Pour lexécuter, vous devrez probablement le faire en tant que ``root`` :"
#: howto/logging-cookbook.rst:2490
msgid ""
"Note that this example uses Python 3.3 because that's where :func:`shutil."
"chown` makes an appearance. This approach should work with any Python "
"version that supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. "
"With pre-3.3 versions, you would need to implement the actual ownership "
"change using e.g. :func:`os.chown`."
msgstr ""
"Notez que cet exemple utilise Python 3.3 car cest là que :func:`shutil."
"chown` fait son apparition. Cette approche devrait fonctionner avec "
"nimporte quelle version de Python prenant en charge :func:`dictConfig` à "
"savoir, Python 2.7, 3.2 ou version ultérieure. Avec les versions antérieures "
"à la 3.3, vous devrez implémenter le changement de propriétaire réel en "
"utilisant par exemple :func:`os.chown`."
#: howto/logging-cookbook.rst:2496
msgid ""
"In practice, the handler-creating function may be in a utility module "
"somewhere in your project. Instead of the line in the configuration::"
msgstr ""
"En pratique, la fonction de création de gestionnaire peut être située dans "
"un module utilitaire ailleurs dans votre projet. Au lieu de cette ligne dans "
"la configuration ::"
#: howto/logging-cookbook.rst:2501
msgid "you could use e.g.::"
msgstr "vous pouvez écrire par exemple ::"
#: howto/logging-cookbook.rst:2505
msgid ""
"where ``project.util`` can be replaced with the actual name of the package "
"where the function resides. In the above working script, using ``'ext://"
"__main__.owned_file_handler'`` should work. Here, the actual callable is "
"resolved by :func:`dictConfig` from the ``ext://`` specification."
msgstr ""
"où ``project.util`` peut être remplacé par le nom réel du paquet où réside "
"la fonction. Dans le script étudié ci-dessus, lutilisation de ``'ext://"
"__main__.owned_file_handler'`` devrait fonctionner. Dans le cas présent, "
"lappelable réel est résolu par :func:`dictConfig` à partir de la "
"spécification ``ext://``."
#: howto/logging-cookbook.rst:2510
msgid ""
"This example hopefully also points the way to how you could implement other "
"types of file change - e.g. setting specific POSIX permission bits - in the "
"same way, using :func:`os.chmod`."
msgstr ""
"Nous espérons qu'à partir de cet exemple vous saurez implémenter dautres "
"types de modification de fichier par ex. définir des bits dautorisation "
"POSIX spécifiques de la même manière, en utilisant :func:`os.chmod`."
#: howto/logging-cookbook.rst:2514
msgid ""
"Of course, the approach could also be extended to types of handler other "
"than a :class:`~logging.FileHandler` - for example, one of the rotating file "
"handlers, or a different type of handler altogether."
msgstr ""
"Bien sûr, lapproche pourrait également être étendue à des types de "
"gestionnaires autres quun :class:`~logging.FileHandler` par exemple, lun "
"des gestionnaires à roulement de fichiers ou un autre type de gestionnaire "
"complètement différent."
#: howto/logging-cookbook.rst:2524
msgid "Using particular formatting styles throughout your application"
msgstr ""
#: howto/logging-cookbook.rst:2526
msgid ""
"In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword "
"parameter which, while defaulting to ``%`` for backward compatibility, "
"allowed the specification of ``{`` or ``$`` to support the formatting "
"approaches supported by :meth:`str.format` and :class:`string.Template`. "
"Note that this governs the formatting of logging messages for final output "
"to logs, and is completely orthogonal to how an individual logging message "
"is constructed."
msgstr ""
#: howto/logging-cookbook.rst:2533
msgid ""
"Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take "
"positional parameters for the actual logging message itself, with keyword "
"parameters used only for determining options for how to handle the logging "
"call (e.g. the ``exc_info`` keyword parameter to indicate that traceback "
"information should be logged, or the ``extra`` keyword parameter to indicate "
"additional contextual information to be added to the log). So you cannot "
"directly make logging calls using :meth:`str.format` or :class:`string."
"Template` syntax, because internally the logging package uses %-formatting "
"to merge the format string and the variable arguments. There would no "
"changing this while preserving backward compatibility, since all logging "
"calls which are out there in existing code will be using %-format strings."
msgstr ""
#: howto/logging-cookbook.rst:2545
msgid ""
"There have been suggestions to associate format styles with specific "
"loggers, but that approach also runs into backward compatibility problems "
"because any existing code could be using a given logger name and using %-"
"formatting."
msgstr ""
#: howto/logging-cookbook.rst:2549
msgid ""
"For logging to work interoperably between any third-party libraries and your "
"code, decisions about formatting need to be made at the level of the "
"individual logging call. This opens up a couple of ways in which alternative "
"formatting styles can be accommodated."
msgstr ""
#: howto/logging-cookbook.rst:2556
msgid "Using LogRecord factories"
msgstr ""
#: howto/logging-cookbook.rst:2558
msgid ""
"In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned "
"above, the logging package gained the ability to allow users to set their "
"own :class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` "
"function. You can use this to set your own subclass of :class:`LogRecord`, "
"which does the Right Thing by overriding the :meth:`~LogRecord.getMessage` "
"method. The base class implementation of this method is where the ``msg % "
"args`` formatting happens, and where you can substitute your alternate "
"formatting; however, you should be careful to support all formatting styles "
"and allow %-formatting as the default, to ensure interoperability with other "
"code. Care should also be taken to call ``str(self.msg)``, just as the base "
"implementation does."
msgstr ""
#: howto/logging-cookbook.rst:2569
msgid ""
"Refer to the reference documentation on :func:`setLogRecordFactory` and :"
"class:`LogRecord` for more information."
msgstr ""
#: howto/logging-cookbook.rst:2574
msgid "Using custom message objects"
msgstr ""
#: howto/logging-cookbook.rst:2576
msgid ""
"There is another, perhaps simpler way that you can use {}- and $- formatting "
"to construct your individual log messages. You may recall (from :ref:"
"`arbitrary-object-messages`) that when logging you can use an arbitrary "
"object as a message format string, and that the logging package will call :"
"func:`str` on that object to get the actual format string. Consider the "
"following two classes::"
msgstr ""
#: howto/logging-cookbook.rst:2601
msgid ""
"Either of these can be used in place of a format string, to allow {}- or $-"
"formatting to be used to build the actual \"message\" part which appears in "
"the formatted log output in place of “%(message)s” or “{message}” or "
"“$message”. If you find it a little unwieldy to use the class names whenever "
"you want to log something, you can make it more palatable if you use an "
"alias such as ``M`` or ``_`` for the message (or perhaps ``__``, if you are "
"using ``_`` for localization)."
msgstr ""
#: howto/logging-cookbook.rst:2609
msgid ""
"Examples of this approach are given below. Firstly, formatting with :meth:"
"`str.format`::"
msgstr ""
#: howto/logging-cookbook.rst:2623
msgid "Secondly, formatting with :class:`string.Template`::"
msgstr ""
#: howto/logging-cookbook.rst:2630
msgid ""
"One thing to note is that you pay no significant performance penalty with "
"this approach: the actual formatting happens not when you make the logging "
"call, but when (and if) the logged message is actually about to be output to "
"a log by a handler. So the only slightly unusual thing which might trip you "
"up is that the parentheses go around the format string and the arguments, "
"not just the format string. Thats because the __ notation is just syntax "
"sugar for a constructor call to one of the ``XXXMessage`` classes shown "
"above."
msgstr ""
#: howto/logging-cookbook.rst:2644
msgid "Configuring filters with :func:`dictConfig`"
msgstr ""
#: howto/logging-cookbook.rst:2646
msgid ""
"You *can* configure filters using :func:`~logging.config.dictConfig`, though "
"it might not be obvious at first glance how to do it (hence this recipe). "
"Since :class:`~logging.Filter` is the only filter class included in the "
"standard library, and it is unlikely to cater to many requirements (it's "
"only there as a base class), you will typically need to define your own :"
"class:`~logging.Filter` subclass with an overridden :meth:`~logging.Filter."
"filter` method. To do this, specify the ``()`` key in the configuration "
"dictionary for the filter, specifying a callable which will be used to "
"create the filter (a class is the most obvious, but you can provide any "
"callable which returns a :class:`~logging.Filter` instance). Here is a "
"complete example::"
msgstr ""
#: howto/logging-cookbook.rst:2699
msgid ""
"This example shows how you can pass configuration data to the callable which "
"constructs the instance, in the form of keyword parameters. When run, the "
"above script will print:"
msgstr ""
#: howto/logging-cookbook.rst:2707
msgid "which shows that the filter is working as configured."
msgstr ""
#: howto/logging-cookbook.rst:2709
msgid "A couple of extra points to note:"
msgstr ""
#: howto/logging-cookbook.rst:2711
msgid ""
"If you can't refer to the callable directly in the configuration (e.g. if it "
"lives in a different module, and you can't import it directly where the "
"configuration dictionary is), you can use the form ``ext://...`` as "
"described in :ref:`logging-config-dict-externalobj`. For example, you could "
"have used the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in "
"the above example."
msgstr ""
#: howto/logging-cookbook.rst:2718
msgid ""
"As well as for filters, this technique can also be used to configure custom "
"handlers and formatters. See :ref:`logging-config-dict-userdef` for more "
"information on how logging supports using user-defined objects in its "
"configuration, and see the other cookbook recipe :ref:`custom-handlers` "
"above."
msgstr ""
#: howto/logging-cookbook.rst:2727
msgid "Customized exception formatting"
msgstr ""
#: howto/logging-cookbook.rst:2729
msgid ""
"There might be times when you want to do customized exception formatting - "
"for argument's sake, let's say you want exactly one line per logged event, "
"even when exception information is present. You can do this with a custom "
"formatter class, as shown in the following example::"
msgstr ""
#: howto/logging-cookbook.rst:2770
msgid "When run, this produces a file with exactly two lines:"
msgstr ""
#: howto/logging-cookbook.rst:2777
msgid ""
"While the above treatment is simplistic, it points the way to how exception "
"information can be formatted to your liking. The :mod:`traceback` module may "
"be helpful for more specialized needs."
msgstr ""
#: howto/logging-cookbook.rst:2784
msgid "Speaking logging messages"
msgstr ""
#: howto/logging-cookbook.rst:2786
msgid ""
"There might be situations when it is desirable to have logging messages "
"rendered in an audible rather than a visible format. This is easy to do if "
"you have text-to-speech (TTS) functionality available in your system, even "
"if it doesn't have a Python binding. Most TTS systems have a command line "
"program you can run, and this can be invoked from a handler using :mod:"
"`subprocess`. It's assumed here that TTS command line programs won't expect "
"to interact with users or take a long time to complete, and that the "
"frequency of logged messages will be not so high as to swamp the user with "
"messages, and that it's acceptable to have the messages spoken one at a time "
"rather than concurrently, The example implementation below waits for one "
"message to be spoken before the next is processed, and this might cause "
"other handlers to be kept waiting. Here is a short example showing the "
"approach, which assumes that the ``espeak`` TTS package is available::"
msgstr ""
#: howto/logging-cookbook.rst:2828
msgid ""
"When run, this script should say \"Hello\" and then \"Goodbye\" in a female "
"voice."
msgstr ""
#: howto/logging-cookbook.rst:2830
msgid ""
"The above approach can, of course, be adapted to other TTS systems and even "
"other systems altogether which can process messages via external programs "
"run from a command line."
msgstr ""
#: howto/logging-cookbook.rst:2838
msgid "Buffering logging messages and outputting them conditionally"
msgstr ""
#: howto/logging-cookbook.rst:2840
msgid ""
"There might be situations where you want to log messages in a temporary area "
"and only output them if a certain condition occurs. For example, you may "
"want to start logging debug events in a function, and if the function "
"completes without errors, you don't want to clutter the log with the "
"collected debug information, but if there is an error, you want all the "
"debug information to be output as well as the error."
msgstr ""
#: howto/logging-cookbook.rst:2847
msgid ""
"Here is an example which shows how you could do this using a decorator for "
"your functions where you want logging to behave this way. It makes use of "
"the :class:`logging.handlers.MemoryHandler`, which allows buffering of "
"logged events until some condition occurs, at which point the buffered "
"events are ``flushed`` - passed to another handler (the ``target`` handler) "
"for processing. By default, the ``MemoryHandler`` flushed when its buffer "
"gets filled up or an event whose level is greater than or equal to a "
"specified threshold is seen. You can use this recipe with a more specialised "
"subclass of ``MemoryHandler`` if you want custom flushing behavior."
msgstr ""
#: howto/logging-cookbook.rst:2857
msgid ""
"The example script has a simple function, ``foo``, which just cycles through "
"all the logging levels, writing to ``sys.stderr`` to say what level it's "
"about to log at, and then actually logging a message at that level. You can "
"pass a parameter to ``foo`` which, if true, will log at ERROR and CRITICAL "
"levels - otherwise, it only logs at DEBUG, INFO and WARNING levels."
msgstr ""
#: howto/logging-cookbook.rst:2863
msgid ""
"The script just arranges to decorate ``foo`` with a decorator which will do "
"the conditional logging that's required. The decorator takes a logger as a "
"parameter and attaches a memory handler for the duration of the call to the "
"decorated function. The decorator can be additionally parameterised using a "
"target handler, a level at which flushing should occur, and a capacity for "
"the buffer (number of records buffered). These default to a :class:`~logging."
"StreamHandler` which writes to ``sys.stderr``, ``logging.ERROR`` and ``100`` "
"respectively."
msgstr ""
#: howto/logging-cookbook.rst:2871
msgid "Here's the script::"
msgstr ""
#: howto/logging-cookbook.rst:2934
msgid "When this script is run, the following output should be observed:"
msgstr ""
#: howto/logging-cookbook.rst:2964
msgid ""
"As you can see, actual logging output only occurs when an event is logged "
"whose severity is ERROR or greater, but in that case, any previous events at "
"lower severities are also logged."
msgstr ""
#: howto/logging-cookbook.rst:2968
msgid "You can of course use the conventional means of decoration::"
msgstr ""
#: howto/logging-cookbook.rst:2978
msgid "Sending logging messages to email, with buffering"
msgstr ""
#: howto/logging-cookbook.rst:2980
msgid ""
"To illustrate how you can send log messages via email, so that a set number "
"of messages are sent per email, you can subclass :class:`~logging.handlers."
"BufferingHandler`. In the following example, which you can adapt to suit "
"your specific needs, a simple test harness is provided which allows you to "
"run the script with command line arguments specifying what you typically "
"need to send things via SMTP. (Run the downloaded script with the ``-h`` "
"argument to see the required and optional arguments.)"
msgstr ""
#: howto/logging-cookbook.rst:3052
msgid ""
"If you run this script and your SMTP server is correctly set up, you should "
"find that it sends eleven emails to the addressee you specify. The first ten "
"emails will each have ten log messages, and the eleventh will have two "
"messages. That makes up 102 messages as specified in the script."
msgstr ""
#: howto/logging-cookbook.rst:3060
msgid "Formatting times using UTC (GMT) via configuration"
msgstr ""
#: howto/logging-cookbook.rst:3062
msgid ""
"Sometimes you want to format times using UTC, which can be done using a "
"class such as ``UTCFormatter``, shown below::"
msgstr ""
#: howto/logging-cookbook.rst:3071
msgid ""
"and you can then use the ``UTCFormatter`` in your code instead of :class:"
"`~logging.Formatter`. If you want to do that via configuration, you can use "
"the :func:`~logging.config.dictConfig` API with an approach illustrated by "
"the following complete example::"
msgstr ""
#: howto/logging-cookbook.rst:3114
msgid "When this script is run, it should print something like:"
msgstr ""
#: howto/logging-cookbook.rst:3121
msgid ""
"showing how the time is formatted both as local time and UTC, one for each "
"handler."
msgstr ""
#: howto/logging-cookbook.rst:3128
msgid "Using a context manager for selective logging"
msgstr ""
#: howto/logging-cookbook.rst:3130
msgid ""
"There are times when it would be useful to temporarily change the logging "
"configuration and revert it back after doing something. For this, a context "
"manager is the most obvious way of saving and restoring the logging context. "
"Here is a simple example of such a context manager, which allows you to "
"optionally change the logging level and add a logging handler purely in the "
"scope of the context manager::"
msgstr ""
#: howto/logging-cookbook.rst:3163
msgid ""
"If you specify a level value, the logger's level is set to that value in the "
"scope of the with block covered by the context manager. If you specify a "
"handler, it is added to the logger on entry to the block and removed on exit "
"from the block. You can also ask the manager to close the handler for you on "
"block exit - you could do this if you don't need the handler any more."
msgstr ""
#: howto/logging-cookbook.rst:3169
msgid ""
"To illustrate how it works, we can add the following block of code to the "
"above::"
msgstr ""
#: howto/logging-cookbook.rst:3187
msgid ""
"We initially set the logger's level to ``INFO``, so message #1 appears and "
"message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the "
"following ``with`` block, and so message #3 appears. After the block exits, "
"the logger's level is restored to ``INFO`` and so message #4 doesn't appear. "
"In the next ``with`` block, we set the level to ``DEBUG`` again but also add "
"a handler writing to ``sys.stdout``. Thus, message #5 appears twice on the "
"console (once via ``stderr`` and once via ``stdout``). After the ``with`` "
"statement's completion, the status is as it was before so message #6 appears "
"(like message #1) whereas message #7 doesn't (just like message #2)."
msgstr ""
#: howto/logging-cookbook.rst:3197
msgid "If we run the resulting script, the result is as follows:"
msgstr ""
#: howto/logging-cookbook.rst:3208
msgid ""
"If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the "
"following, which is the only message written to ``stdout``:"
msgstr ""
#: howto/logging-cookbook.rst:3216
msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:"
msgstr ""
#: howto/logging-cookbook.rst:3226
msgid ""
"In this case, the message #5 printed to ``stdout`` doesn't appear, as "
"expected."
msgstr ""
#: howto/logging-cookbook.rst:3228
msgid ""
"Of course, the approach described here can be generalised, for example to "
"attach logging filters temporarily. Note that the above code works in Python "
"2 as well as Python 3."
msgstr ""
#: howto/logging-cookbook.rst:3236
msgid "A CLI application starter template"
msgstr ""
#: howto/logging-cookbook.rst:3238
msgid "Here's an example which shows how you can:"
msgstr ""
#: howto/logging-cookbook.rst:3240
msgid "Use a logging level based on command-line arguments"
msgstr ""
#: howto/logging-cookbook.rst:3241
msgid ""
"Dispatch to multiple subcommands in separate files, all logging at the same "
"level in a consistent way"
msgstr ""
#: howto/logging-cookbook.rst:3243
msgid "Make use of simple, minimal configuration"
msgstr ""
#: howto/logging-cookbook.rst:3245
msgid ""
"Suppose we have a command-line application whose job is to stop, start or "
"restart some services. This could be organised for the purposes of "
"illustration as a file ``app.py`` that is the main script for the "
"application, with individual commands implemented in ``start.py``, ``stop."
"py`` and ``restart.py``. Suppose further that we want to control the "
"verbosity of the application via a command-line argument, defaulting to "
"``logging.INFO``. Here's one way that ``app.py`` could be written::"
msgstr ""
#: howto/logging-cookbook.rst:3294
msgid ""
"And the ``start``, ``stop`` and ``restart`` commands can be implemented in "
"separate modules, like so for starting::"
msgstr ""
#: howto/logging-cookbook.rst:3307
msgid "and thus for stopping::"
msgstr ""
#: howto/logging-cookbook.rst:3328
msgid "and similarly for restarting::"
msgstr ""
#: howto/logging-cookbook.rst:3349
msgid ""
"If we run this application with the default log level, we get output like "
"this:"
msgstr ""
#: howto/logging-cookbook.rst:3362
msgid ""
"The first word is the logging level, and the second word is the module or "
"package name of the place where the event was logged."
msgstr ""
#: howto/logging-cookbook.rst:3365
msgid ""
"If we change the logging level, then we can change the information sent to "
"the log. For example, if we want more information:"
msgstr ""
#: howto/logging-cookbook.rst:3382
msgid "And if we want less:"
msgstr ""
#: howto/logging-cookbook.rst:3390
msgid ""
"In this case, the commands don't print anything to the console, since "
"nothing at ``WARNING`` level or above is logged by them."
msgstr ""
#: howto/logging-cookbook.rst:3396
msgid "A Qt GUI for logging"
msgstr ""
#: howto/logging-cookbook.rst:3398
msgid ""
"A question that comes up from time to time is about how to log to a GUI "
"application. The `Qt <https://www.qt.io/>`_ framework is a popular cross-"
"platform UI framework with Python bindings using `PySide2 <https://pypi.org/"
"project/PySide2/>`_ or `PyQt5 <https://pypi.org/project/PyQt5/>`_ libraries."
msgstr ""
#: howto/logging-cookbook.rst:3404
msgid ""
"The following example shows how to log to a Qt GUI. This introduces a simple "
"``QtHandler`` class which takes a callable, which should be a slot in the "
"main thread that does GUI updates. A worker thread is also created to show "
"how you can log to the GUI from both the UI itself (via a button for manual "
"logging) as well as a worker thread doing work in the background (here, just "
"logging messages at random levels with random short delays in between)."
msgstr ""
#: howto/logging-cookbook.rst:3411
msgid ""
"The worker thread is implemented using Qt's ``QThread`` class rather than "
"the :mod:`threading` module, as there are circumstances where one has to use "
"``QThread``, which offers better integration with other ``Qt`` components."
msgstr ""
#: howto/logging-cookbook.rst:3415
msgid ""
"The code should work with recent releases of either ``PySide2`` or "
"``PyQt5``. You should be able to adapt the approach to earlier versions of "
"Qt. Please refer to the comments in the code snippet for more detailed "
"information."
msgstr ""
#: howto/logging-cookbook.rst:3629
msgid "Logging to syslog with RFC5424 support"
msgstr ""
#: howto/logging-cookbook.rst:3631
msgid ""
"Although :rfc:`5424` dates from 2009, most syslog servers are configured by "
"detault to use the older :rfc:`3164`, which hails from 2001. When "
"``logging`` was added to Python in 2003, it supported the earlier (and only "
"existing) protocol at the time. Since RFC5424 came out, as there has not "
"been widespread deployment of it in syslog servers, the :class:`~logging."
"handlers.SysLogHandler` functionality has not been updated."
msgstr ""
#: howto/logging-cookbook.rst:3638
msgid ""
"RFC 5424 contains some useful features such as support for structured data, "
"and if you need to be able to log to a syslog server with support for it, "
"you can do so with a subclassed handler which looks something like this::"
msgstr ""
#: howto/logging-cookbook.rst:3704
msgid ""
"You'll need to be familiar with RFC 5424 to fully understand the above code, "
"and it may be that you have slightly different needs (e.g. for how you pass "
"structural data to the log). Nevertheless, the above should be adaptable to "
"your speciric needs. With the above handler, you'd pass structured data "
"using something like this::"
msgstr ""
#: howto/logging-cookbook.rst:3718
msgid "How to treat a logger like an output stream"
msgstr ""
#: howto/logging-cookbook.rst:3720
msgid ""
"Sometimes, you need to interface to a third-party API which expects a file-"
"like object to write to, but you want to direct the API's output to a "
"logger. You can do this using a class which wraps a logger with a file-like "
"API. Here's a short script illustrating such a class:"
msgstr ""
#: howto/logging-cookbook.rst:3760
msgid "When this script is run, it prints"
msgstr ""
#: howto/logging-cookbook.rst:3767
msgid ""
"You could also use ``LoggerWriter`` to redirect ``sys.stdout`` and ``sys."
"stderr`` by doing something like this:"
msgstr ""
#: howto/logging-cookbook.rst:3777
msgid ""
"You should do this *after* configuring logging for your needs. In the above "
"example, the :func:`~logging.basicConfig` call does this (using the ``sys."
"stderr`` value *before* it is overwritten by a ``LoggerWriter`` instance). "
"Then, you'd get this kind of result:"
msgstr ""
#: howto/logging-cookbook.rst:3790
msgid ""
"Of course, the examples above show output according to the format used by :"
"func:`~logging.basicConfig`, but you can use a different formatter when you "
"configure logging."
msgstr ""
#: howto/logging-cookbook.rst:3794
msgid ""
"Note that with the above scheme, you are somewhat at the mercy of buffering "
"and the sequence of write calls which you are intercepting. For example, "
"with the definition of ``LoggerWriter`` above, if you have the snippet"
msgstr ""
#: howto/logging-cookbook.rst:3803
msgid "then running the script results in"
msgstr ""
#: howto/logging-cookbook.rst:3821
msgid ""
"As you can see, this output isn't ideal. That's because the underlying code "
"which writes to ``sys.stderr`` makes mutiple writes, each of which results "
"in a separate logged line (for example, the last three lines above). To get "
"around this problem, you need to buffer things and only output log lines "
"when newlines are seen. Let's use a slghtly better implementation of "
"``LoggerWriter``:"
msgstr ""
#: howto/logging-cookbook.rst:3846
msgid ""
"This just buffers up stuff until a newline is seen, and then logs complete "
"lines. With this approach, you get better output:"
msgstr ""
#: howto/logging-cookbook.rst:3862
msgid "Patterns to avoid"
msgstr ""
#: howto/logging-cookbook.rst:3864
msgid ""
"Although the preceding sections have described ways of doing things you "
"might need to do or deal with, it is worth mentioning some usage patterns "
"which are *unhelpful*, and which should therefore be avoided in most cases. "
"The following sections are in no particular order."
msgstr ""
#: howto/logging-cookbook.rst:3870
msgid "Opening the same log file multiple times"
msgstr ""
#: howto/logging-cookbook.rst:3872
msgid ""
"On Windows, you will generally not be able to open the same file multiple "
"times as this will lead to a \"file is in use by another process\" error. "
"However, on POSIX platforms you'll not get any errors if you open the same "
"file multiple times. This could be done accidentally, for example by:"
msgstr ""
#: howto/logging-cookbook.rst:3877
msgid ""
"Adding a file handler more than once which references the same file (e.g. by "
"a copy/paste/forget-to-change error)."
msgstr ""
#: howto/logging-cookbook.rst:3880
msgid ""
"Opening two files that look different, as they have different names, but are "
"the same because one is a symbolic link to the other."
msgstr ""
#: howto/logging-cookbook.rst:3883
msgid ""
"Forking a process, following which both parent and child have a reference to "
"the same file. This might be through use of the :mod:`multiprocessing` "
"module, for example."
msgstr ""
#: howto/logging-cookbook.rst:3887
msgid ""
"Opening a file multiple times might *appear* to work most of the time, but "
"can lead to a number of problems in practice:"
msgstr ""
#: howto/logging-cookbook.rst:3890
msgid ""
"Logging output can be garbled because multiple threads or processes try to "
"write to the same file. Although logging guards against concurrent use of "
"the same handler instance by multiple threads, there is no such protection "
"if concurrent writes are attempted by two different threads using two "
"different handler instances which happen to point to the same file."
msgstr ""
#: howto/logging-cookbook.rst:3896
msgid ""
"An attempt to delete a file (e.g. during file rotation) silently fails, "
"because there is another reference pointing to it. This can lead to "
"confusion and wasted debugging time - log entries end up in unexpected "
"places, or are lost altogether. Or a file that was supposed to be moved "
"remains in place, and grows in size unexpectedly despite size-based rotation "
"being supposedly in place."
msgstr ""
#: howto/logging-cookbook.rst:3903
msgid ""
"Use the techniques outlined in :ref:`multiple-processes` to circumvent such "
"issues."
msgstr ""
#: howto/logging-cookbook.rst:3907
msgid "Using loggers as attributes in a class or passing them as parameters"
msgstr ""
#: howto/logging-cookbook.rst:3909
msgid ""
"While there might be unusual cases where you'll need to do this, in general "
"there is no point because loggers are singletons. Code can always access a "
"given logger instance by name using ``logging.getLogger(name)``, so passing "
"instances around and holding them as instance attributes is pointless. Note "
"that in other languages such as Java and C#, loggers are often static class "
"attributes. However, this pattern doesn't make sense in Python, where the "
"module (and not the class) is the unit of software decomposition."
msgstr ""
#: howto/logging-cookbook.rst:3918
msgid ""
"Adding handlers other than :class:`NullHandler` to a logger in a library"
msgstr ""
#: howto/logging-cookbook.rst:3920
msgid ""
"Configuring logging by adding handlers, formatters and filters is the "
"responsibility of the application developer, not the library developer. If "
"you are maintaining a library, ensure that you don't add handlers to any of "
"your loggers other than a :class:`~logging.NullHandler` instance."
msgstr ""
#: howto/logging-cookbook.rst:3926
msgid "Creating a lot of loggers"
msgstr ""
#: howto/logging-cookbook.rst:3928
msgid ""
"Loggers are singletons that are never freed during a script execution, and "
"so creating lots of loggers will use up memory which can't then be freed. "
"Rather than create a logger per e.g. file processed or network connection "
"made, use the :ref:`existing mechanisms <context-info>` for passing "
"contextual information into your logs and restrict the loggers created to "
"those describing areas within your application (generally modules, but "
"occasionally slightly more fine-grained than that)."
msgstr ""
#: howto/logging-cookbook.rst:3939
msgid "Other resources"
msgstr ""
#: howto/logging-cookbook.rst:3952
msgid ":ref:`Basic Tutorial <logging-basic-tutorial>`"
msgstr ""
#: howto/logging-cookbook.rst:3954
msgid ":ref:`Advanced Tutorial <logging-advanced-tutorial>`"
msgstr ""