An example Logging to multiple destinations in Logging Cookbook shows that we can configure logging‘s behavior once and then use the new behavior everywhere.
In one file LogAgent.py, we can configure logging‘s behavior as below.
// LogAgent.py
import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
In another file A, we can use logging like below.
from LogAgent import *
logger1 = logging.getLogger('myapp.area1')
logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
In another file B, we can use logging in the same way.
from LogAgent import *
logger2 = logging.getLogger('myapp.area2')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')