Logging for Automation Scripts (logging module)
Why logging
Section titled “Why logging”Logs help you answer:
- what happened?
- when did it happen?
- why did it fail?
Basic setup
Section titled “Basic setup”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
Section titled “Rotation”For large logs, use RotatingFileHandler.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading