As a python developer, in your scripts, you must provide information for the user and for yours. I’m sure you’re thinking on print statement, but this isn’t recommended. Today, I want to show why and give you some good tips about logging python module. This module is intended for logging (obviously), but maybe you dont know that this module provides:
- Level logging: You can log in different level, filter outputs.
- Multi logging: You can log into a file and stdout at the same time.
- Hierarchical logging: You can define a hierarchical model of loggers.
This is very useful for defining for example logging to a file and stdout at the same time, you or the user can see the info-level output in stdout but all debug-level output is logged at file for debugging purpose. It’s a better alternative to define a lot of print statements in your code for debug and then erase them or comment them when they’re not necessary. Enough words, let’s go to some examples of use. The very basic example is:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/temp/myapp.log',
filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')
This examples configure logging module to filter messages below debug-level, format line defines output shown before every message and third and fourth lines define that logging will be made on a that file in write mode. This will print all lines, because debug, info and warning are equal or above filter’s debug-level. A better example involves a loggers.conf file which defines loggers and options.
[loggers]
keys=rootL,exampleL
[handlers]
keys=rootH,exampleH
[formatters]
keys=exampleF
[logger_root]
level=NOTSET
handlers=rootH
[logger_exampleL]
level=DEBUG
handlers=exampleH
propagate=1
qualname=exampleL
[handler_rootH]
class=StreamHandler
level=NOTSET
formatter=exampleF
args=(sys.stdout,)
[handler_exampleH]
class=FileHandler
level=DEBUG
formatter=exampleF
args=('python.log', 'w')
[formatter_exmapleF]
format=%(asctime)s %(levelname)-8s %(message)s
datefmt=
class=logging.Formatter
To use this configuration file, you must to do:
import logging, logging.config logging.config.fileConfig(<file name>)
logger = logging.getLogger("exampleL")
logger.debug('A debug message')
logger.info('Some information')
logger.warning('A shot across the bows')
For more information about logging module, visit this.
I hope you enjoy, but this is all for now. Stay tuned to get more interesting stuff.