Learn & Build

Practical Programming Tutorials & Projects

,

Adding Logging to a Python Script (Beginner-Friendly Guide)

In a previous post, I shared a simple Python script to automate daily tasks by organizing files.
While the script works, it lacks one important thing: visibility.

If something goes wrong, we don’t know why.

In this post, I’ll show how to add basic logging to a Python script so we can see what it’s doing while it runs.
This is a small change, but it’s an important step toward writing more reliable automation scripts.

Why Logging Matters

Logging helps you:

  • Understand what your script is doing
  • Debug issues faster
  • Track failures and successes
  • Make scripts production-ready

In DevOps and automation, logging is not optional — it’s essential.


Using Python’s Built-in Logging Module

Python comes with a built-in logging module, so no external libraries are needed.

Here’s a basic setup:

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

This configures:

  • Log level
  • Timestamp
  • Readable output format

Adding Logging to the File Organizer Script

Here’s an updated version of the previous script with logging added:




import os
import shutil
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

source_folder = "files"

for filename in os.listdir(source_folder):
    file_path = os.path.join(source_folder, filename)

    if os.path.isfile(file_path):
        extension = filename.split(".")[-1]
        folder_name = extension.upper() + "_files"
        folder_path = os.path.join(source_folder, folder_name)

        os.makedirs(folder_path, exist_ok=True)
        shutil.move(file_path, folder_path)

        logging.info(f"Moved {filename} to {folder_name}")


What Changed

  • Added logging configuration at the top
  • Logged each file move
  • Gained visibility into script behavior

Now, when the script runs, you can clearly see what it’s doing.


Why This Is a DevOps-Style Improvement

This small change:

  • Makes automation observable
  • Aligns with production practices
  • Prepares scripts for cron jobs or containers

These are the same principles used in real DevOps workflows.


What I’ll Build Next

In the next post, I’ll:

  • Add error handling
  • Make the script configurable
  • Explore running it automatically using cron

Leave a comment

About

Learn & Build is a personal blog about learning programming by building real projects. It documents practical tutorials, small experiments, and lessons learned along the way.