Skip to content

Logging for Automation Scripts (logging module)

Why logging

Logs help you answer:

  • what happened?
  • when did it happen?
  • why did it fail?

Basic setup

logging_to_file.py
import logging
 
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
    handlers=[
        logging.FileHandler("job.log", encoding="utf-8"),
        logging.StreamHandler(),
    ],
)
 
log = logging.getLogger("job")
log.info("started")
logging_to_file.py
import logging
 
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
    handlers=[
        logging.FileHandler("job.log", encoding="utf-8"),
        logging.StreamHandler(),
    ],
)
 
log = logging.getLogger("job")
log.info("started")

Rotation

For large logs, use RotatingFileHandlerRotatingFileHandler.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

Exercise 2 โ€“ Join Paths with os.path.join

Exercise 3 โ€“ Write and Read a File

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did