using basicConfig:
# package/__main__.py
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
using fileConfig:
# package/__main__.py
import logging
import logging.config
logging.config.fileConfig('logging.conf')
and then create every logger using:
# package/submodule.py
# or
# package/subpackage/submodule.py
import logging
log = logging.getLogger(__name__)
log.info("Hello logging!")
You can see a lots of example out there get logger at module level. They looks harmless, but actually, there is a pitfall – Python logging
module respects all created logger before you load the configuration from a file.
Since Python2.7, a new argument name disable_existing_loggers
to fileConfig
and dictConfig
(as a parameter in schema) is added, by setting it to False
, problem mentioned above can be solved. For example:
if __name__ == '__main__':
from logging.config import fileConfig
fileConfig('logging.conf', disable_existing_loggers=False)
main()