logging.handlers --- Logging handlers¶
Code source : Lib/logging/handlers.py
Les gestionnaires suivants, très utiles, sont fournis dans le paquet. Notez que trois des gestionnaires (StreamHandler, FileHandler et NullHandler) sont en réalité définis dans le module logging lui-même, mais qu’ils sont documentés ici avec les autres gestionnaires.
Gestionnaire à flux — StreamHandler¶
La classe StreamHandler, du paquet logging, envoie les sorties de journalisation dans des flux tels que sys.stdout, sys.stderr ou n’importe quel objet fichier-compatible (ou, plus précisément, tout objet qui gère les méthodes write() et flush()).
- class logging.StreamHandler(stream=None)¶
Renvoie une nouvelle instance de la classe
StreamHandler. Si stream est spécifié, l’instance l’utilise pour les sorties de journalisation ; autrement elle utilise sys.stderr.- emit(record)¶
Si un formateur est spécifié, il est utilisé pour formater l’enregistrement. L’enregistrement est ensuite écrit dans le flux, suivi par
terminator. Si une information d’exception est présente, elle est formatée en utilisanttraceback.print_exception()puis ajoutée aux flux.
- flush()¶
Purge le flux en appelant sa méthode
flush(). Notez que la méthodeclose()est héritée deHandlerdonc elle n'écrit rien. Par conséquent, un appel explicite àflush()peut parfois s'avérer nécessaire.
- setStream(stream)¶
Définit le flux de l’instance à la valeur spécifiée, si elle est différente. L’ancien flux est purgé avant que le nouveau flux ne soit établi.
- Paramètres:
stream -- le flux que le gestionnaire doit utiliser.
- Renvoie:
the old stream, if the stream was changed, or
Noneif it wasn't.
Ajouté dans la version 3.7.
- terminator¶
Chaine de caractères utilisée comme marqueur de fin lors de l’écriture formatée d'un enregistrement dans un flux. La valeur par défaut est
'\n'.Si vous ne voulez pas marquer de fin de ligne, il faut définir l’attribut
terminatorà la chaîne de caractères vide.Dans des versions antérieures, le marqueur de fin était codé en dur sous la forme
'\n'.Ajouté dans la version 3.2.
Gestionnaire à fichier — FileHandler¶
La classe FileHandler, du paquet logging, envoie les sorties de journalisation dans un fichier. Elle hérite des fonctionnalités de sortie de StreamHandler.
- class logging.FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)¶
Returns a new instance of the
FileHandlerclass. The specified file is opened and used as the stream for logging. If mode is not specified,'a'is used. If encoding is notNone, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call toemit(). By default, the file grows indefinitely. If errors is specified, it's used to determine how encoding errors are handled.Modifié dans la version 3.6: L'argument filename accepte les objets
Pathaussi bien que les chaînes de caractères.Modifié dans la version 3.9: ajout du paramètre errors.
- close()¶
Ferme le fichier.
Gestionnaire à puits sans fond — NullHandler¶
Ajouté dans la version 3.1.
La classe NullHandler, située dans le paquet principal logging, ne produit aucun formatage ni sortie. C’est essentiellement un gestionnaire « fantôme » destiné aux développeurs de bibliothèques.
- class logging.NullHandler¶
Renvoie une nouvelle instance de la classe
NullHandler.- emit(record)¶
Cette méthode ne fait rien.
- handle(record)¶
Cette méthode ne fait rien.
- createLock()¶
Cette méthode renvoie
Nonepour le verrou, étant donné qu’il n’y a aucun flux d'entrée-sortie sous-jacent dont l’accès doit être sérialisé.
Voir Configuration de la journalisation pour une bibliothèque pour plus d’information sur l'utilisation de NullHandler.
Gestionnaire à fichier avec surveillance — WatchedFileHandler¶
La classe WatchedFileHandler, du module logging.handlers, est une classe FileHandler qui surveille le fichier dans lequel elle écrit. Si le fichier est modifié, il est fermé et rouvert en utilisant le nom du fichier.
Le fichier peut être modifié par des programmes tels que newsyslog ou logrotate qui assurent le roulement des fichiers de journalisation. Ce gestionnaire, destiné à une utilisation sous Unix-Linux, surveille le fichier pour voir s’il a changé depuis la dernière écriture (un fichier est considéré comme modifié si son nœud d’index ou le périphérique auquel il est rattaché a changé). Si le fichier a changé, l’ancien flux vers ce fichier est fermé, et le fichier est ouvert pour établir un nouveau flux.
Ce gestionnaire n’est pas approprié pour une utilisation sous Windows, car sous Windows les fichiers de journalisation ouverts ne peuvent être ni déplacés, ni renommés — la journalisation ouvre les fichiers avec des verrous exclusifs — de telle sorte qu’il n’y a pas besoin d’un tel gestionnaire. En outre, ST_INO n’est pas géré par Windows ; stat() renvoie toujours zéro pour cette valeur.
- class logging.handlers.WatchedFileHandler(filename, mode='a', encoding=None, delay=False, errors=None)¶
Returns a new instance of the
WatchedFileHandlerclass. The specified file is opened and used as the stream for logging. If mode is not specified,'a'is used. If encoding is notNone, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call toemit(). By default, the file grows indefinitely. If errors is provided, it determines how encoding errors are handled.Modifié dans la version 3.6: L'argument filename accepte les objets
Pathaussi bien que les chaînes de caractères.Modifié dans la version 3.9: ajout du paramètre errors.
- reopenIfNeeded()¶
Vérifie si le fichier a changé. Si c’est le cas, le flux existant est purgé et fermé et le fichier est rouvert, généralement avant d'effectuer l’écriture de l'enregistrement dans le fichier.
Ajouté dans la version 3.6.
- emit(record)¶
Écrit l’enregistrement dans le fichier, mais appelle d’abord
reopenIfNeeded()pour rouvrir le fichier s’il a changé.
Base des gestionnaires à roulement — BaseRotatingHandler¶
La classe BaseRotatingHandler, du module logging.handlers, est la classe de base pour les gestionnaires à roulement, RotatingFileHandler et TimedRotatingFileHandler. Il ne faut pas créer des instances de cette classe, mais surcharger ses attributs et méthodes.
- class logging.handlers.BaseRotatingHandler(filename, mode, encoding=None, delay=False, errors=None)¶
Les paramètres sont les mêmes que pour
FileHandler. Les attributs sont :- namer¶
Si cet attribut est un qu’appelable, la méthode
rotation_filename()délègue sa logique à cet appelable. Les paramètres passés à l’appelable sont ceux passés àrotation_filename().Note
la fonction namer est appelée de nombreuses fois durant le roulement ; elle doit donc être aussi simple et rapide que possible. Elle doit aussi renvoyer toujours la même sortie pour une entrée donnée, autrement le comportement du roulement pourrait être différent de celui attendu.
It's also worth noting that care should be taken when using a namer to preserve certain attributes in the filename which are used during rotation. For example,
RotatingFileHandlerexpects to have a set of log files whose names contain successive integers, so that rotation works as expected, andTimedRotatingFileHandlerdeletes old log files (based on thebackupCountparameter passed to the handler's initializer) by determining the oldest files to delete. For this to happen, the filenames should be sortable using the date/time portion of the filename, and a namer needs to respect this. (If a namer is wanted that doesn't respect this scheme, it will need to be used in a subclass ofTimedRotatingFileHandlerwhich overrides thegetFilesToDelete()method to fit in with the custom naming scheme.)Ajouté dans la version 3.3.
- rotator¶
Si cet attribut est un appelable, il se substitue à la méthode
rotate(). Les paramètres passés à l’appelable sont ceux passés àrotate().Ajouté dans la version 3.3.
- rotation_filename(default_name)¶
Modifie le nom du fichier d’un fichier de journalisation lors du roulement.
Cette méthode sert à pouvoir produire un nom de fichier personnalisé.
L’implémentation par défaut appelle l’attribut namer du gestionnaire, si c’est un appelable, lui passant le nom par défaut. Si l’attribut n’est pas un appelable (le défaut est
None), le nom est renvoyé tel quel.- Paramètres:
default_name -- le nom par défaut du fichier de journalisation.
Ajouté dans la version 3.3.
- rotate(source, dest)¶
Lors du roulement, effectue le roulement du journal courant.
L’implémentation par défaut appelle l’attribut rotator du gestionnaire, si c’est un appelable, lui passant les arguments source et dest. Si l’attribut n’est pas un appelable (le défaut est
None), le nom de la source est simplement renommé avec la destination.- Paramètres:
source -- le nom du fichier source. Il s’agit normalement du nom du fichier, par exemple
"test.log".dest -- le nom du fichier de destination. Il s’agit normalement du nom donné à la source après le roulement, par exemple
"test.log.1".
Ajouté dans la version 3.3.
La raison d’être de ces attributs est de vous épargner la création d’une sous-classe — vous pouvez utiliser les mêmes appels pour des instances de RotatingFileHandler et TimedRotatingFileHandler. Si l'appelable namer ou rotator lève une exception, elle est gérée de la même manière que n’importe quelle exception levée lors d'un appel à emit(), c'est-à-dire par la méthode handleError() du gestionnaire.
Si vous avez besoin de faire d’importantes modifications au processus de roulement, surchargez les méthodes.
Pour un exemple, voir Utilisation d’un rotateur et d’un nom pour personnaliser la rotation des journaux.
Gestionnaire à roulement de fichiers — RotatingFileHandler¶
La classe RotatingFileHandler, du module logging.handlers, gère le roulement des fichiers de journalisation sur disque.
- class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)¶
Renvoie une nouvelle instance de la classe
RotatingFileHandler. Le fichier spécifié est ouvert et utilisé comme flux de sortie pour la journalisation. Si mode n’est pas spécifié,'a'est utilisé. Si encoding n’est pas àNone, il est utilisé pour ouvrir le fichier avec cet encodage. Si delay est à true, alors l’ouverture du fichier est reportée au premier appel deemit(). Par défaut, le fichier croit indéfiniment. Si errors est spécifié, il détermine comment sont gérées les erreurs d’encodage.Utilisez les valeurs maxBytes et backupCount pour autoriser le roulement du fichier (rollover) à une taille prédéterminée. Quand la taille limite est sur le point d’être dépassée, le fichier est fermé et un nouveau fichier est automatiquement ouvert pour le remplacer. Un roulement se produit dès que le fichier de journalisation actuel atteint une taille proche de maxBytes ; si maxBytes ou backupCount est à 0, le roulement ne se produit jamais, donc en temps normal il convient de définir backupCount à au moins 1, et avoir une valeur de maxBytes non nulle. Quand backupCount est non nul, le système sauvegarde les anciens fichiers de journalisation en ajoutant à leur nom les suffixes
".1",".2"et ainsi de suite. Par exemple, avec un backupCount de 5 etapp.logcomme radical du fichier, on obtientapp.log,app.log.1,app.log.2, jusqu’àapp.log.5. Le fichier dans lequel on écrit est toujoursapp.log. Quand ce fichier est rempli, il est fermé et renommé enapp.log.1, et si les fichiersapp.log.1,app.log.2, etc. existent, alors ils sont renommés enapp.log.2,app.log.3etc. respectivement.Modifié dans la version 3.6: L'argument filename accepte les objets
Pathaussi bien que les chaînes de caractères.Modifié dans la version 3.9: ajout du paramètre errors.
- doRollover()¶
Effectue un roulement, comme décrit ci-dessus.
- emit(record)¶
Écrit l'enregistrement dans le fichier, effectuant un roulement au besoin comme décrit précédemment.
- shouldRollover(record)¶
See if the supplied record would cause the file to exceed the configured size limit.
Gestionnaire à roulement de fichiers périodique — TimedRotatingFileHandler¶
La classe TimedRotatingFileHandler du module logging.handlers gère le roulement des fichiers de journalisation sur le disque selon un intervalle de temps spécifié.
- class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)¶
Renvoie une nouvelle instance de la classe
TimedRotatingFileHandler. Le fichier spécifié est ouvert et utilisé comme flux de sortie pour la journalisation. Au moment du roulement, elle met également à jour le suffixe du nom du fichier. L'intervalle entre les roulements est déterminé par les valeurs de when et interval.Utilisez when pour spécifier le type de interval. Ses valeurs possibles sont décrites ci-dessous. Notez qu'elles ne sont pas sensibles à la casse.
Valeur
Type d’intervalle
Rôle de atTime
'S'Secondes
Ignoré
'M'Minutes
Ignoré
'H'Heures
Ignoré
'D'Jours
Ignoré
'W0'-'W6'Jour de la semaine (0 = lundi)
Utilisé pour calculer le moment du roulement
'midnight'Roulement du fichier à minuit, si atTime n’est pas spécifié, sinon à l’heure atTime
Utilisé pour calculer le moment du roulement
Pour un roulement selon les jours de la semaine, mettez la valeur W0 pour lundi, W1 pour mardi, et ainsi de suite jusqu’à W6 pour dimanche. Dans ce cas, la valeur indiquée pour interval n’est pas utilisée.
Le système sauvegarde les anciens fichiers de journalisation en ajoutant une extension au nom du fichier. Les extensions sont basées sur la date et l’heure, au format strftime
%Y-%m-%d_%H-%M-%Sou le début de celui-ci, selon l’intervalle du roulement.Le premier calcul de la date du prochain roulement (quand le gestionnaire est créé) dépend de la dernière date de modification d’un fichier de journalisation existant, ou à défaut de la date actuelle.
Si utc est vrai, les temps sont UTC, sinon l'heure locale est utilisée.
Si backupCount est non nul, au plus backupCount fichiers sont sauvegardés. Si des fichiers supplémentaires devaient être créés par le jeu du roulement, les plus vieux seraient supprimés. La logique de suppression détermine les fichiers à supprimer selon l'intervalle, donc changer cette valeur peut conduire à ce que certains fichiers anciens restent sur le disque.
Si delay est à true, alors l’ouverture du fichier est reportée au premier appel de
emit().Si le roulement doit se produire « à minuit » ou « à un jour fixe de la semaine » et si atTime n'est pas
None, ce doit être une instance dedatetime.timequi définit l'heure de la journée à laquelle le roulement se produit. Dans ce cas, la valeur de atTime ne sert qu'à déterminer la date du roulement initial, la date des roulements ultérieurs est déterminée par le calcul standard de l'intervalle.Si errors est définit, il définit comment traiter les erreurs d'encodage.
Note
la date du premier roulement est déterminée lors de l'initialisation du gestionnaire. Ce n'est que lors d'un roulement que la date du roulement suivant n'est déterminée, et un roulement n'a lieu que si des entrées doivent être journalisées. Gardez bien cela à l'esprit pour ne pas avoir de surprises. Par exemple, un gestionnaire avec un intervalle « d'une minute » ne produira pas nécessairement des fichiers avec des dates (dans le nom desdits fichiers) séparées d'une minute. Si une application génère des journaux plus fréquemment que toutes les minutes au cours de son exécution, alors dans ce cas vous obtiendrez des fichiers avec des temps séparés d'une minute. Si la même application ne produit une entrée de journal que toutes les cinq minutes, il y aura des sauts dans les dates des fichiers produits qui correspondront aux moments où rien n'a été produit (et donc où aucun roulement n'a eu lieu).
Modifié dans la version 3.4: ajout du paramètre atTime.
Modifié dans la version 3.6: L'argument filename accepte les objets
Pathaussi bien que les chaînes de caractères.Modifié dans la version 3.9: ajout du paramètre errors.
- doRollover()¶
Effectue un roulement, comme décrit ci-dessus.
- emit(record)¶
Écrit l'enregistrement dans le fichier, effectuant un roulement au besoin comme décrit précédemment.
- getFilesToDelete()¶
Returns a list of filenames which should be deleted as part of rollover. These
- shouldRollover(record)¶
See if enough time has passed for a rollover to occur and if it has, compute the next rollover time.
Gestionnaire à connecteur — SocketHandler¶
The SocketHandler class, located in the logging.handlers module,
sends logging output to a network socket. The base class uses a TCP socket.
- class logging.handlers.SocketHandler(host, port)¶
Returns a new instance of the
SocketHandlerclass intended to communicate with a remote machine whose address is given by host and port.Modifié dans la version 3.4: If
portis specified asNone, a Unix domain socket is created using the value inhost- otherwise, a TCP socket is created.- close()¶
Closes the socket.
- emit()¶
Pickles the record's attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. If the connection was previously lost, re-establishes the connection. To unpickle the record at the receiving end into a
LogRecord, use themakeLogRecord()function.
- handleError()¶
Handles an error which has occurred during
emit(). The most likely cause is a lost connection. Closes the socket so that we can retry on the next event.
- makeSocket()¶
This is a factory method which allows subclasses to define the precise type of socket they want. The default implementation creates a TCP socket (
socket.SOCK_STREAM).
- makePickle(record)¶
Pickles the record's attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket. The details of this operation are equivalent to:
data = pickle.dumps(record_attr_dict, 1) datalen = struct.pack('>L', len(data)) return datalen + data
Note that pickles aren't completely secure. If you are concerned about security, you may want to override this method to implement a more secure mechanism. For example, you can sign pickles using HMAC and then verify them on the receiving end, or alternatively you can disable unpickling of global objects on the receiving end.
- send(packet)¶
Send a pickled byte-string packet to the socket. The format of the sent byte-string is as described in the documentation for
makePickle().This function allows for partial sends, which can happen when the network is busy.
- createSocket()¶
Tries to create a socket; on failure, uses an exponential back-off algorithm. On initial failure, the handler will drop the message it was trying to send. When subsequent messages are handled by the same instance, it will not try connecting until some time has passed. The default parameters are such that the initial delay is one second, and if after that delay the connection still can't be made, the handler will double the delay each time up to a maximum of 30 seconds.
This behaviour is controlled by the following handler attributes:
retryStart(initial delay, defaulting to 1.0 seconds).retryFactor(multiplier, defaulting to 2.0).retryMax(maximum delay, defaulting to 30.0 seconds).
This means that if the remote listener starts up after the handler has been used, you could lose messages (since the handler won't even attempt a connection until the delay has elapsed, but just silently drop messages during the delay period).
DatagramHandler¶
The DatagramHandler class, located in the logging.handlers
module, inherits from SocketHandler to support sending logging messages
over UDP sockets.
- class logging.handlers.DatagramHandler(host, port)¶
Returns a new instance of the
DatagramHandlerclass intended to communicate with a remote machine whose address is given by host and port.Note
As UDP is not a streaming protocol, there is no persistent connection between an instance of this handler and host. For this reason, when using a network socket, a DNS lookup might have to be made each time an event is logged, which can introduce some latency into the system. If this affects you, you can do a lookup yourself and initialize this handler using the looked-up IP address rather than the hostname.
Modifié dans la version 3.4: If
portis specified asNone, a Unix domain socket is created using the value inhost- otherwise, a UDP socket is created.- emit()¶
Pickles the record's attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a
LogRecord, use themakeLogRecord()function.
- makeSocket()¶
The factory method of
SocketHandleris here overridden to create a UDP socket (socket.SOCK_DGRAM).
- send(s)¶
Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for
SocketHandler.makePickle().
SysLogHandler¶
The SysLogHandler class, located in the logging.handlers module,
supports sending logging messages to a remote or local Unix syslog.
- class logging.handlers.SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM, timeout=None)¶
Returns a new instance of the
SysLogHandlerclass intended to communicate with a remote Unix machine whose address is given by address in the form of a(host, port)tuple. If address is not specified,('localhost', 514)is used. The address is used to open a socket. An alternative to providing a(host, port)tuple is providing an address as a string, for example '/dev/log'. In this case, a Unix domain socket is used to send the message to the syslog. If facility is not specified,LOG_USERis used. The type of socket opened depends on the socktype argument, which defaults tosocket.SOCK_DGRAMand thus opens a UDP socket. To open a TCP socket (for use with the newer syslog daemons such as rsyslog), specify a value ofsocket.SOCK_STREAM. If timeout is specified, it sets a timeout (in seconds) for the socket operations. This can help prevent the program from hanging indefinitely if the syslog server is unreachable. By default, timeout isNone, meaning no timeout is applied.Note that if your server is not listening on UDP port 514,
SysLogHandlermay appear not to work. In that case, check what address you should be using for a domain socket - it's system dependent. For example, on Linux it's usually '/dev/log' but on OS/X it's '/var/run/syslog'. You'll need to check your platform and use the appropriate address (you may need to do this check at runtime if your application needs to run on several platforms). On Windows, you pretty much have to use the UDP option.Note
On macOS 12.x (Monterey), Apple has changed the behaviour of their syslog daemon - it no longer listens on a domain socket. Therefore, you cannot expect
SysLogHandlerto work on this system.See gh-91070 for more information.
Modifié dans la version 3.2: socktype was added.
Modifié dans la version 3.14: timeout was added.
- close()¶
Closes the socket to the remote host.
- createSocket()¶
Tries to create a socket and, if it's not a datagram socket, connect it to the other end. This method is called during handler initialization, but it's not regarded as an error if the other end isn't listening at this point - the method will be called again when emitting an event, if there is no socket at that point.
Ajouté dans la version 3.11.
- emit(record)¶
The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.
Modifié dans la version 3.2.1: (See: bpo-12168.) In earlier versions, the message sent to the syslog daemons was always terminated with a NUL byte, because early versions of these daemons expected a NUL terminated message - even though it's not in the relevant specification (RFC 5424). More recent versions of these daemons don't expect the NUL byte but strip it off if it's there, and even more recent daemons (which adhere more closely to RFC 5424) pass the NUL byte on as part of the message.
To enable easier handling of syslog messages in the face of all these differing daemon behaviours, the appending of the NUL byte has been made configurable, through the use of a class-level attribute,
append_nul. This defaults toTrue(preserving the existing behaviour) but can be set toFalseon aSysLogHandlerinstance in order for that instance to not append the NUL terminator.Modifié dans la version 3.3: (See: bpo-12419.) In earlier versions, there was no facility for an "ident" or "tag" prefix to identify the source of the message. This can now be specified using a class-level attribute, defaulting to
""to preserve existing behaviour, but which can be overridden on aSysLogHandlerinstance in order for that instance to prepend the ident to every message handled. Note that the provided ident must be text, not bytes, and is prepended to the message exactly as is.
- encodePriority(facility, priority)¶
Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.
The symbolic
LOG_values are defined inSysLogHandlerand mirror the values defined in thesys/syslog.hheader file.Priorities
Name (string)
Symbolic value
alertLOG_ALERT
critoucriticalLOG_CRIT
debugLOG_DEBUG
emergoupanicLOG_EMERG
errouerrorLOG_ERR
infoLOG_INFO
noticeLOG_NOTICE
warnouwarningLOG_WARNING
Facilities
Name (string)
Symbolic value
authLOG_AUTH
authprivLOG_AUTHPRIV
cronLOG_CRON
daemonLOG_DAEMON
ftpLOG_FTP
kernLOG_KERN
lprLOG_LPR
mailLOG_MAIL
newsLOG_NEWS
syslogLOG_SYSLOG
userLOG_USER
uucpLOG_UUCP
local0LOG_LOCAL0
local1LOG_LOCAL1
local2LOG_LOCAL2
local3LOG_LOCAL3
local4LOG_LOCAL4
local5LOG_LOCAL5
local6LOG_LOCAL6
local7LOG_LOCAL7
- mapPriority(levelname)¶
Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps
DEBUG,INFO,WARNING,ERRORandCRITICALto the equivalent syslog names, and all other level names to 'warning'.
NTEventLogHandler¶
The NTEventLogHandler class, located in the logging.handlers
module, supports sending logging messages to a local Windows NT, Windows 2000 or
Windows XP event log. Before you can use it, you need Mark Hammond's Win32
extensions for Python installed.
- class logging.handlers.NTEventLogHandler(appname, dllname=None, logtype='Application')¶
Returns a new instance of the
NTEventLogHandlerclass. The appname is used to define the application name as it appears in the event log. An appropriate registry entry is created using this name. The dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified,'win32service.pyd'is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own .dll or .exe which contains the message definitions you want to use in the event log). The logtype is one of'Application','System'or'Security', and defaults to'Application'.- close()¶
At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.
- emit(record)¶
Determines the message ID, event category and event type, and then logs the message in the NT event log.
- getEventCategory(record)¶
Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.
- getEventType(record)¶
Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in
__init__()to a dictionary which contains mappings forDEBUG,INFO,WARNING,ERRORandCRITICAL. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler's typemap attribute.
- getMessageID(record)¶
Returns the message ID for the record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in
win32service.pyd.
SMTPHandler¶
The SMTPHandler class, located in the logging.handlers module,
supports sending logging messages to an email address via SMTP.
- class logging.handlers.SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)¶
Returns a new instance of the
SMTPHandlerclass. The instance is initialized with the from and to addresses and subject line of the email. The toaddrs should be a list of strings. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. If you use a string, the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the credentials argument.To specify the use of a secure protocol (TLS), pass in a tuple to the secure argument. This will only be used when authentication credentials are supplied. The tuple should be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the
smtplib.SMTP.starttls()method.)A timeout can be specified for communication with the SMTP server using the timeout argument.
Modifié dans la version 3.3: Added the timeout parameter.
- emit(record)¶
Formats the record and sends it to the specified addressees.
- getSubject(record)¶
If you want to specify a subject line which is record-dependent, override this method.
MemoryHandler¶
The MemoryHandler class, located in the logging.handlers module,
supports buffering of logging records in memory, periodically flushing them to a
target handler. Flushing occurs whenever the buffer is full, or when an
event of a certain severity or greater is seen.
MemoryHandler is a subclass of the more general
BufferingHandler, which is an abstract class. This buffers logging
records in memory. Whenever each record is added to the buffer, a check is made
by calling shouldFlush() to see if the buffer should be flushed. If it
should, then flush() is expected to do the flushing.
- class logging.handlers.BufferingHandler(capacity)¶
Initializes the handler with a buffer of the specified capacity. Here, capacity means the number of logging records buffered.
- emit(record)¶
Append the record to the buffer. If
shouldFlush()returns true, callflush()to process the buffer.
- flush()¶
For a
BufferingHandlerinstance, flushing means that it sets the buffer to an empty list. This method can be overwritten to implement more useful flushing behavior.
- shouldFlush(record)¶
Return
Trueif the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.
- class logging.handlers.MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)¶
Returns a new instance of the
MemoryHandlerclass. The instance is initialized with a buffer size of capacity (number of records buffered). If flushLevel is not specified,ERRORis used. If no target is specified, the target will need to be set usingsetTarget()before this handler does anything useful. If flushOnClose is specified asFalse, then the buffer is not flushed when the handler is closed. If not specified or specified asTrue, the previous behaviour of flushing the buffer will occur when the handler is closed.Modifié dans la version 3.6: The flushOnClose parameter was added.
- flush()¶
For a
MemoryHandlerinstance, flushing means just sending the buffered records to the target, if there is one. The buffer is also cleared when buffered records are sent to the target. Override if you want different behavior.
- setTarget(target)¶
Sets the target handler for this handler.
- shouldFlush(record)¶
Checks for buffer full or a record at the flushLevel or higher.
HTTPHandler¶
The HTTPHandler class, located in the logging.handlers module,
supports sending logging messages to a web server, using either GET or
POST semantics.
- class logging.handlers.HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None)¶
Returns a new instance of the
HTTPHandlerclass. The host can be of the formhost:port, should you need to use a specific port number. If no method is specified,GETis used. If secure is true, a HTTPS connection will be used. The context parameter may be set to assl.SSLContextinstance to configure the SSL settings used for the HTTPS connection. If credentials is specified, it should be a 2-tuple consisting of userid and password, which will be placed in a HTTP 'Authorization' header using Basic authentication. If you specify credentials, you should also specify secure=True so that your userid and password are not passed in cleartext across the wire.Modifié dans la version 3.5: The context parameter was added.
- mapLogRecord(record)¶
Provides a dictionary, based on
record, which is to be URL-encoded and sent to the web server. The default implementation just returnsrecord.__dict__. This method can be overridden if e.g. only a subset ofLogRecordis to be sent to the web server, or if more specific customization of what's sent to the server is required.
- emit(record)¶
Sends the record to the web server as a URL-encoded dictionary. The
mapLogRecord()method is used to convert the record to the dictionary to be sent.
Note
Since preparing a record for sending it to a web server is not the same as a generic formatting operation, using
setFormatter()to specify aFormatterfor aHTTPHandlerhas no effect. Instead of callingformat(), this handler callsmapLogRecord()and thenurllib.parse.urlencode()to encode the dictionary in a form suitable for sending to a web server.
QueueHandler¶
Ajouté dans la version 3.2.
The QueueHandler class, located in the logging.handlers module,
supports sending logging messages to a queue, such as those implemented in the
queue or multiprocessing modules.
Along with the QueueListener class, QueueHandler can be used
to let handlers do their work on a separate thread from the one which does the
logging. This is important in web applications and also other service
applications where threads servicing clients need to respond as quickly as
possible, while any potentially slow operations (such as sending an email via
SMTPHandler) are done on a separate thread.
- class logging.handlers.QueueHandler(queue)¶
Returns a new instance of the
QueueHandlerclass. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it's used as-is by theenqueue()method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can useSimpleQueueinstances for queue.Note
If you are using
multiprocessing, you should avoid usingSimpleQueueand instead usemultiprocessing.Queue.Avertissement
The
multiprocessingmodule uses an internal logger created and accessed viaget_logger().multiprocessing.Queuewill logDEBUGlevel messages upon items being queued. If those log messages are processed by aQueueHandlerusing the samemultiprocessing.Queueinstance, it will cause a deadlock or infinite recursion.- emit(record)¶
Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the
handleError()method is called to handle the error. This can result in the record silently being dropped (iflogging.raiseExceptionsisFalse) or a message printed tosys.stderr(iflogging.raiseExceptionsisTrue).
- prepare(record)¶
Prepares a record for queuing. The object returned by this method is enqueued.
The base implementation formats the record to merge the message, arguments, exception and stack information, if present. It also removes unpickleable items from the record in-place. Specifically, it overwrites the record's
msgandmessageattributes with the merged message (obtained by calling the handler'sformat()method), and sets theargs,exc_infoandexc_textattributes toNone.You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.
Note
The base implementation formats the message with arguments, sets the
messageandmsgattributes to the formatted message and sets theargsandexc_textattributes toNoneto allow pickling and to prevent further attempts at formatting. This means that a handler on theQueueListenerside won't have the information to do custom formatting, e.g. of exceptions. You may wish to subclassQueueHandlerand override this method to e.g. avoid settingexc_texttoNone. Note that themessage/msg/argschanges are related to ensuring the record is pickleable, and you might or might not be able to avoid doing that depending on whether yourargsare pickleable. (Note that you may have to consider not only your own code but also code in any libraries that you use.)
- enqueue(record)¶
Enqueues the record on the queue using
put_nowait(); you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation.
- listener¶
When created via configuration using
dictConfig(), this attribute will contain aQueueListenerinstance for use with this handler. Otherwise, it will beNone.Ajouté dans la version 3.12.
QueueListener¶
Ajouté dans la version 3.2.
The QueueListener class, located in the logging.handlers
module, supports receiving logging messages from a queue, such as those
implemented in the queue or multiprocessing modules. The
messages are received from a queue in an internal thread and passed, on
the same thread, to one or more handlers for processing. While
QueueListener is not itself a handler, it is documented here
because it works hand-in-hand with QueueHandler.
Along with the QueueHandler class, QueueListener can be used
to let handlers do their work on a separate thread from the one which does the
logging. This is important in web applications and also other service
applications where threads servicing clients need to respond as quickly as
possible, while any potentially slow operations (such as sending an email via
SMTPHandler) are done on a separate thread.
- class logging.handlers.QueueListener(queue, *handlers, respect_handler_level=False)¶
Returns a new instance of the
QueueListenerclass. The instance is initialized with the queue to send messages to and a list of handlers which will handle entries placed on the queue. The queue can be any queue-like object; it's passed as-is to thedequeue()method, which needs to know how to get messages from it. The queue is not required to have the task tracking API (though it's used if available), which means that you can useSimpleQueueinstances for queue.Note
If you are using
multiprocessing, you should avoid usingSimpleQueueand instead usemultiprocessing.Queue.If
respect_handler_levelisTrue, a handler's level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.Modifié dans la version 3.5: The
respect_handler_levelargument was added.Modifié dans la version 3.14:
QueueListenercan now be used as a context manager viawith. When entering the context, the listener is started. When exiting the context, the listener is stopped.__enter__()returns theQueueListenerobject.- dequeue(block)¶
Dequeues a record and return it, optionally blocking.
The base implementation uses
get(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
- prepare(record)¶
Prepare a record for handling.
This implementation just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers.
- handle(record)¶
Handle a record.
This just loops through the handlers offering them the record to handle. The actual object passed to the handlers is that which is returned from
prepare().
- start()¶
Starts the listener.
This starts up a background thread to monitor the queue for LogRecords to process.
Modifié dans la version 3.14: Raises
RuntimeErrorif called and the listener is already running.
- stop()¶
Stops the listener.
This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed.
- enqueue_sentinel()¶
Writes a sentinel to the queue to tell the listener to quit. This implementation uses
put_nowait(). You may want to override this method if you want to use timeouts or work with custom queue implementations.Ajouté dans la version 3.3.
Voir aussi
- Module
logging Référence d'API pour le module de journalisation.
- Module
logging.config API de configuration pour le module de journalisation.