Site Tools


import-logging

import logging

import logging is a Python import that logs messages at different severity levels: DEBUG, INFO, WARNING, ERROR, CRITICAL. Use it instead of print() for production code.

Example

# Python
# description: configure logging, log at different levels
 
import logging
 
# Configure basic logging
logging.basicConfig(level=logging.INFO, 
                    format="%(asctime)s - %(levelname)s - %(message)s")
 
# Log messages
logging.debug("Debug message (not shown)")
logging.info("Application started")
logging.warning("This is a warning")
logging.error("An error occurred")
logging.critical("Critical failure")
 
# Get logger for a module
logger = logging.getLogger(__name__)
logger.info("Module-specific message")
 
# Log exceptions
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Division by zero occurred")

Common functions

  • logging.basicConfig(level, format, filename): configure logging
  • logging.debug(msg): debug message
  • logging.info(msg): info message
  • logging.warning(msg): warning message
  • logging.error(msg): error message
  • logging.critical(msg): critical message
  • logging.getLogger(name): get logger for module
  • logger.exception(msg): log exception with traceback
  • Levels: DEBUG < INFO < WARNING < ERROR < CRITICAL
import-logging.md · Last modified: by 127.0.0.1