I have a small python project that has the following structure –
Project
-- pkg01
-- test01.py
-- pkg02
-- test02.py
-- logging.conf
I plan to use the default logging module to print messages to stdout and a log file.
To use the logging module, some initialization is required –
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('pyApp')
logger.info('testing')
At present, I perform this initialization in every module before I start logging messages. Is it possible to perform this initialization only once in one place such that the same settings are reused by logging all over the project?
Best Answer
Best practice is, in each module, to have a logger defined like this:
near the top of the module, and then in other code in the module do e.g.
If you need to subdivide logging activity inside a module, use e.g.
and log to
loggerA
andloggerB
as appropriate.In your main program or programs, do e.g.:
or
See here for logging from multiple modules, and here for logging configuration for code which will be used as a library module by other code.
Update: When calling
fileConfig()
, you may want to specifydisable_existing_loggers=False
if you're using Python 2.6 or later (see the docs for more information). The default value isTrue
for backward compatibility, which causes all existing loggers to be disabled byfileConfig()
unless they or their ancestor are explicitly named in the configuration. With the value set toFalse
, existing loggers are left alone. If using Python 2.7/Python 3.2 or later, you may wish to consider thedictConfig()
API which is better thanfileConfig()
as it gives more control over the configuration.