Script Monitoring

Monitor all your scripts regardless of language

Automated scripts are the backbone of modern IT infrastructure. Maintenance scripts, data processing, migrations, synchronizations, exports - these programs often run in the background, without direct human supervision.

The major problem with scripts is their silent nature. A PHP script that fails with a fatal error doesn't notify anyone. A Python script with a broken dependency stops quietly. A Bash script that can't find the expected file terminates with an error code that nobody checks.

Heartbeat monitoring solves this fundamental problem: instead of checking the script itself, we verify that it signaled successful execution. If the expected signal doesn't arrive, an alert is triggered. Simple, effective, universal.

Why Monitor Your Scripts?

Every unmonitored script is a potential ticking time bomb:

  • Silent failures: A crashing script generally sends no notification. Without monitoring, you'll never know it failed.
  • Scheduling issues: Misconfigured cron, restarted server, disabled scheduled task - the script never starts and nobody notices.
  • Progressive degradation: A script taking longer and longer to execute may signal a growing problem (database growth, memory leaks).
  • Fragile dependencies: A system update, a removed module, a modified API - and your script stops working without warning.

Error Types That Monitoring Detects

Heartbeat monitoring detects three main categories of problems:

Startup Errors

  • Misconfigured cron or scheduler
  • Insufficient permissions on script or files
  • Uninitialized environment (missing variables)

Execution Errors

  • Unhandled exception or fatal error
  • Timeout exceeded (script too slow)
  • Inaccessible resource (database, file, API)

Logic Errors

  • Script completes but produces incorrect result
  • Partial processing (some items fail)
  • Validation failed after processing

Code Examples by Language

Heartbeat integration takes just a few lines of code, regardless of your language:

Bash

#!/bin/bash
# script_backup.sh - Example with heartbeat monitoring

HEARTBEAT_URL="https://monitao.com/ping/YOUR_TOKEN"

# Error handling function
handle_error() {
    curl -s "$HEARTBEAT_URL/fail?error=$1" > /dev/null
    exit 1
}

# Main script execution
echo "Starting backup..."

if ! rsync -av /data /backup; then
    handle_error "rsync_failed"
fi

if ! gzip /backup/data.tar; then
    handle_error "gzip_failed"
fi

# Success ping at the end
curl -s "$HEARTBEAT_URL" > /dev/null
echo "Backup completed successfully"

The ping is only sent if all steps succeed. On error, a fail ping is sent with details.

PHP

getMessage()));
    error_log("Script failed: " . $e->getMessage());
    exit(1);
}

The try/catch block ensures the ping is only sent on complete success. Errors are logged and reported.

Python

#!/usr/bin/env python3
# script_sync.py - Example with heartbeat monitoring

import requests
import sys

HEARTBEAT_URL = "https://monitao.com/ping/YOUR_TOKEN"

def main():
    try:
        # Business logic
        data = fetch_remote_data()
        processed = transform_data(data)
        save_results(processed)

        # Success ping
        requests.get(HEARTBEAT_URL, timeout=10)
        print("Synchronization completed")

    except Exception as e:
        # Fail ping
        requests.get(f"{HEARTBEAT_URL}/fail",
                    params={"error": str(e)},
                    timeout=10)
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()

The requests module handles HTTP calls cleanly. The timeout prevents blocking on network issues.

Node.js

// script_process.js - Example with heartbeat monitoring

const HEARTBEAT_URL = "https://monitao.com/ping/YOUR_TOKEN";

async function main() {
    try {
        // Business logic
        const data = await fetchData();
        const result = await processData(data);
        await saveResult(result);

        // Success ping
        await fetch(HEARTBEAT_URL);
        console.log("Processing completed");

    } catch (error) {
        // Fail ping
        await fetch(`${HEARTBEAT_URL}/fail?error=${encodeURIComponent(error.message)}`);
        console.error("Error:", error.message);
        process.exit(1);
    }
}

main();

Async/await makes the code readable. Node.js 18+ native fetch simplifies integration.

Integration Patterns

Several strategies are available depending on your architecture:

  • End-of-script ping: The simplest pattern - add the HTTP call as the last instruction. If the script fails before, the ping isn't sent.
  • Global try/catch: Wrap all logic in a try/catch block. Success ping in try, fail ping in catch.
  • Conditional ping: Verify the result before sending the ping. A script can "complete" without producing the correct result.
  • Wrapper script: An encompassing script that calls the main script and handles the heartbeat. Useful for scripts you can't modify.

Best Practices

For effective script monitoring:

  • Test manually first: Run the script by hand at least once before scheduling. Verify the ping arrives correctly.
  • Add timeout to ping: A network issue shouldn't block your script. Use a 5-10 second timeout on the HTTP call.
  • Log before pinging: On error, log details locally BEFORE sending the fail ping. If the ping also fails, you'll still have the log.
  • One heartbeat per script: Don't reuse the same heartbeat for multiple scripts. You'd lose detection granularity.

Script Monitoring Checklist

  • Script tested manually with success
  • Heartbeat created in MoniTao with correct timeout
  • Ping call added at end of script
  • Error handling with fail ping implemented
  • Timeout configured on HTTP ping call
  • First scheduled execution verified

Frequently Asked Questions

My PHP script crashes with a fatal error. Is the ping sent?

No, a fatal error (parse error, out of memory, etc.) stops execution immediately. The ping won't have time to be sent. That's precisely the point of heartbeat monitoring: the missing ping triggers the alert.

How do I monitor a script that runs for 2 hours?

Configure a 2.5 to 3 hour timeout in MoniTao (normal duration + 25-50% margin). For very long scripts, add intermediate progress pings to detect stalls before the global timeout.

Can I monitor scripts on multiple servers?

Yes, each script can use the same heartbeat if you just want to know that at least one server executes it. For individual monitoring, create one heartbeat per server with an explicit name (backup-server-1, backup-server-2).

Does the ping add latency to my script?

About 50-150ms depending on your connection. That's negligible for 99% of scripts. If it's critical, you can make the call asynchronous (fire-and-forget) in Bash or use promises in Node.js.

My script uses a VPN. Can the ping go through?

It depends on your VPN configuration. If traffic to monitao.com is blocked, configure an exception or use a local proxy that forwards pings externally.

Can I send metadata with the ping?

Yes, add GET parameters to the URL: ?duration=120&items=5000&status=partial. This data is stored and visible in the heartbeat history.

Make Your Automated Scripts Reliable

Automated scripts are essential to your infrastructure's smooth operation. Backups, synchronizations, imports, exports, maintenance - these critical processes cannot be left unsupervised. A silently failing script is a ticking time bomb.

Heartbeat monitoring with MoniTao transforms every script into a supervised process. A few lines of code are enough to be certain your scripts run as expected, and to be alerted immediately when something goes wrong.

Ready to Sleep Soundly?

Start free, no credit card required.