Logging best practices

  • Be professional and clear
  • Be concise and use normal capitalization
  • Use the appropriate logging level
    • Debug: for anything that happens in the program
    • Error: self-explanatory
    • Info: for recording user driven or system specific actions
  • Provide useful information
    • E.g. if a function failed to read a file, make sure the logging mentions the path that was looked for

Python's logging library

Basic config:

import logging

logging.basicConfig(
    filename='./results.log',
    level=logging.INFO,
    filemode='w',
    format='%(name)s - %(levelname)s - %(message)s')

The level arguments indicates the lowest logging level that will be recorded. E.g. if it would have been logging.WARNING, info statements would not be recorded in this log, but warning and error messages would.

The formatting here uses old formatting style, but this is on purpose. The logging library implemented lazy evaluation of variable interpolation with this syntax, meaning that if the logging statement is not logged because it does not have the minimum log level, the string is also not interpolated. This saves compute.

Then instead of using print statements you can use logging.info(message), logging.warning(message) or logging.error(message)