Skip to content
Python

Logging

Configure and use the logging module.

By EZ4Code Team
logginglogging

Code

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[
        logging.FileHandler("app.log", encoding="utf-8"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

logger.debug("Debug info")
logger.info("Info")
logger.warning("Warning")
logger.error("error")
logger.exception("Exception (with stacktrace)")  # Only used in except

Explanation

The logging module provides leveled logging, outputting to both file and console simultaneously.

More Python Snippets