0Pricing
Web Scraping & Bots · Lektion

Logging und Fehlerbehandlung für Bots

Entwickeln Sie robuste einfache Bots, indem Sie strukturiertes Logging und eine graceful Fehlerbehandlung ergänzen, damit Fehler sichtbar und behebbar sind.

Logging und Fehlerbehandlung für Bots ist eine kostenlose Web Scraping & Bots-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Web Scraping & Bots-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Web Scraping & Bots-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

Why Bots Need Logs

A bot runs unattended, often on a schedule. When something breaks, you are not watching. Logging leaves a trail so you can diagnose what happened after the fact.

Without logs, a silent failure can go unnoticed for days.

print() Is Not Logging

Beginners use print(), but it has no levels, no timestamps, and no easy way to redirect to a file. Python's logging module solves all of this.

print('something happened')  # no level, no time, hard to manage

Setting Up Logging

Configure logging once at startup. Set a format with a timestamp and a level, and choose where output goes.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s'
)
log = logging.getLogger('bot')
log.info('Bot started')

Log Levels

Levels let you control verbosity:

  • DEBUG detailed tracing.
  • INFO normal progress.
  • WARNING something odd but recoverable.
  • ERROR an operation failed.
  • CRITICAL the bot cannot continue.
log.debug('fetched 12 rows')
log.warning('retrying after timeout')
log.error('login failed')

Logging to a File

For unattended bots, write logs to a file so you can review them later. A rotating handler caps file size.

from logging.handlers import RotatingFileHandler

handler = RotatingFileHandler('bot.log', maxBytes=1_000_000, backupCount=3)
log.addHandler(handler)

Catching Exceptions

Wrap risky operations in try/except so one failure does not crash the whole run. Log the error with context.

try:
    submit_form(data)
except Exception as e:
    log.error('form submission failed: %s', e)

Logging Full Tracebacks

Use log.exception inside an except block to capture the full stack trace, which is invaluable for debugging.

try:
    risky()
except Exception:
    log.exception('unexpected error in risky()')

Retrying Transient Failures

Network blips are common. Catch them and retry a few times before giving up, logging each attempt.

for attempt in range(3):
    try:
        fetch()
        break
    except ConnectionError:
        log.warning('attempt %d failed, retrying', attempt + 1)
else:
    log.error('all attempts failed')

Failing Loudly

Silent failures are dangerous. For critical errors, escalate: send an alert email, write a marker file, or exit with a non-zero code so a scheduler notices.

import sys
if not data:
    log.critical('no data scraped, aborting')
    sys.exit(1)

Clean Shutdown

Always release resources even on error. A finally block (or context managers) guarantees browsers close and files flush regardless of what went wrong.

try:
    run_bot()
finally:
    driver.quit()
    log.info('bot finished')

Structured Logging Context

Attach context to each log line, such as the current URL or item id, so when you scan a long log you immediately know which record a message refers to.

log.info('scraped item %s from %s', item_id, url)

Quick Check

Test your understanding of bot logging and error handling.

Recap

You learned to make simple bots resilient: use the logging module instead of print, choose appropriate levels, log to rotating files, catch and log exceptions with tracebacks, retry transient errors, fail loudly on critical issues, and shut down cleanly.

Häufig gestellte Fragen

Ist die Lektion „Logging und Fehlerbehandlung für Bots“ kostenlos?

Ja — der vollständige Text von „Logging und Fehlerbehandlung für Bots“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Web Scraping & Bots-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Web Scraping & Bots-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Logging und Fehlerbehandlung für Bots“?

Entwickeln Sie robuste einfache Bots, indem Sie strukturiertes Logging und eine graceful Fehlerbehandlung ergänzen, damit Fehler sichtbar und behebbar sind. Du übst Web Scraping & Bots mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Web Scraping & Bots zu starten?

Keine Vorkenntnisse erforderlich. Web Scraping & Bots auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.

Wie lange dauert die Lektion „Logging und Fehlerbehandlung für Bots“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Web Scraping & Bots-Lektion Code schreiben und ausführen?

Ja. Jede Web Scraping & Bots-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Ziele von Bots definieren
  2. Einfache Formularübermittlungen automatisieren
  3. Grundlegende Aufgaben planen
  4. Logging und Fehlerbehandlung für Bots
← Zurück zu Web Scraping & Bots