daniel-s
4/12/2017 - 2:03 PM

Logging

Logging

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!")

Do not get logger at the module level unless disable_existing_loggers is False

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()
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


import os
from datetime import datetime
log_file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'logs', '{}.log'.format(datetime.utcnow().strftime('%Y%m')))

fh = logging.FileHandler(log_file_path)
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter('%(levelname)s:%(name)s:%(asctime)s:%(message)s'))
logger.addHandler(fh)