Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Last active July 2, 2017 13:13
Show Gist options
  • Save dsaiztc/857a79832f32ff1056870a27ee44d042 to your computer and use it in GitHub Desktop.
Save dsaiztc/857a79832f32ff1056870a27ee44d042 to your computer and use it in GitHub Desktop.
Logging
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)

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment