background preloader

Logging

Facebook Twitter

Logging Cookbook. This page contains a number of recipes related to logging, which have been found useful in the past. Using logging in multiple modules 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: Here is the auxiliary module: The output looks like this: Multiple handlers and formatters Loggers are plain Python objects. Notice that the ‘application’ code does not care about multiple handlers. The ability to create new handlers with higher- or lower-severity filters can be very helpful when writing and testing an application. Configuration server example. Écrire des logs en Python. Good morning… Au lieu de mettre des print() partout qu’il va falloir retirer après et qui en plus ne servent à rien dans un processus daemonisé, utiliser les facilités de logging de Python peut se révéler un bon investissement.

Écrire des logs en Python

Investissement car le module logging est du même genre que urllib2, datetime ou os.path : on peut tout faire avec mais vaut mieux avoir la doc sous la main. Pour les gens pressés Avant de se lancer dans les explications, voici le snippet qui permet d’afficher les informations à l’écran et dans un fichier de log : Cette config va afficher : Hello Testing foo sur la console Et : 2013-03-08 11:37:31,311 :: INFO :: Hello 2013-03-08 11:37:31,411 :: WARNING :: Testing foo Dans le fichier de activity.log. Python: log uncaught exceptions with sys.excepthook. You ever notice how when your script dies because of some uncaught error, you don’t get that error in your log files?

Python: log uncaught exceptions with sys.excepthook

This post walks through how to make sure that you log that uncaught exception. This is a trivial script that will raise an uncaught exception (code available here): $ cat rgl/kaboom1.py # vim: set expandtab ts=4 sw=4 filetype=python: import logging def f(): return g() def g(): return h() def h(): return i() def i(): 1/0 if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, filename='/tmp/kaboom1.log', filemode='w') logging.debug('About to do f().') f() Notice the helpful traceback: $ python rgl/kaboom1.py Traceback (most recent call last): File "rgl/kaboom1.py", line 28, in <module> f() File "rgl/kaboom1.py", line 9, in f return g() File "rgl/kaboom1.py", line 13, in g return h() File "rgl/kaboom1.py", line 17, in h return i() File "rgl/kaboom1.py", line 21, in i 1/0 ZeroDivisionError: integer division or modulo by zero logging.error(ex) logging.error(str(ex))