​Hands-On Guide: Adding Automated Logging & Error Handling to Python Scripts

When running automated Python scripts—whether they are market scanners, Telegram alert bots, or data scrapers—unforeseen network drops or API rate limits can cause silent crashes. If your script stops running in the background without leaving a trace, you miss critical market events.


In this hands-on guide, we will implement Python’s built-in logging module and robust exception handling to keep your scripts stable and trackable.


---------------------------------------------------


1. Why Use Logging Instead of Print Statements?

While print() statements are great for quick terminal checks, they disappear when your terminal session closes. The Python logging module allows you to:

• Write error messages and event timestamps directly to a local file (e.g., scanner.log).

• Categorize logs by severity levels (INFO, WARNING, ERROR, CRITICAL).

• Review execution history long after your script has run in the background.


---------------------------------------------------


2. Setting Up the Logging Configuration

Here is how to configure a clean logging setup in your Python script:


import logging


# Configure log file output and format

logging.basicConfig(

    filename='script_activity.log',

    level=logging.INFO,

    format='%(asctime)s - %(levelname)s - %(message)s',

    datefmt='%Y-%m-%d %H:%M:%S'

)


logging.info("Script initialized successfully.")


---------------------------------------------------


3. Implementing Robust Try-Except Exception Handling

Network requests and API endpoints are prone to intermittent timeouts. Wrapping your core logic in try-except blocks prevents crashes:


import time

import requests

import logging


logging.basicConfig(filename='scanner.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def fetch_data():

    url = "https://api.example.com/v1/ticker"

    try:

        response = requests.get(url, timeout=10)

        response.raise_for_status() # Raise error for bad HTTP codes (404, 500, etc.)

        return response.json()

    except requests.exceptions.Timeout:

        logging.warning("API Request timed out. Retrying on next cycle.")

    except requests.exceptions.ConnectionError:

        logging.error("Network connection error occurred. Check mobile data/Wi-Fi.")

    except Exception as e:

        logging.critical(f"Unexpected error encountered: {e}")

    return None


def main():

    logging.info("Starting automated monitoring loop...")

    while True:

        data = fetch_data()

        if data:

            logging.info(f"Data retrieved successfully: {data}")

        else:

            logging.info("Skipping cycle due to missing data.")

        

        time.sleep(60)


if __name__ == "__main__":

    main()


---------------------------------------------------


4. Reviewing Logs in Termux

If you are running your script on mobile via Termux, you can inspect your error logs anytime without stopping the execution loop:

• Use the nano or cat command to read your log file:

  cat scanner.log


---------------------------------------------------


Final Thoughts

Adding structured logging and error handling transforms fragile scripts into production-ready automation tools. Your background tasks will now handle network interruptions gracefully and record every event for easy debugging.


Stay tuned for our upcoming guide on building custom MQL5 indicators in MetaEditor!


Comments

Popular posts from this blog

​Hands-On Guide: Optimizing Mobile Data & Network Stability for MT5 & Python Scanners

​Hands-On Guide: Auto-Reconnecting WebSocket Streams in Python

​Hands-On Guide: Adding Stop Loss, Take Profit, and Trade Execution to Your MQL5 EA