quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Logging anti-patterns #129

Open amorgun opened 5 years ago

amorgun commented 5 years ago
  1. Using print instead of loging
  2. Using root logger by logging.info or logging.getLogger() instead of logging.getLogger(__name__)
  3. Configuring a logger on import E.g.
    
    import logging
    logger = logging.getLogger(__name__)
    logger.addHandler(logging.StreamHandler(sys.stdout))

if name == 'main': main()

This often happens after replacing `print` with `logging`
4. Using `logging.getLogger(__file__)` instead of `logging.getLogger(__name__)`
5. Sharing a logger across multiple files
E.g.

foo.py

LOGGER = logging.getLogger(name)

bar.py

from foo import LOGGER

6. Unnecessary calculations of logging arguments

Bad

logger.debug('Message with %s', expensive_func())

Good

if logger.isEnabledFor(logging.DEBUG): logger.debug('Message with %s', expensive_func())

Docs: https://docs.python.org/3/howto/logging.html#optimization
7. Not using built-in string formatting features

Bad

logger.info('Some data: %s', repr(data))

Good

logger.info('Some data: %r', data)