Bot のロギングとエラーハンドリング
構造化ロギングとグレースフルなエラーハンドリングを追加し、障害を把握して復旧できる、堅牢なシンプル Bot を構築します。
「Bot のロギングとエラーハンドリング」はCoddyKit上の無料Web Scraping & Botsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb Scraping & Bots学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web Scraping & Botsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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 manageSetting 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:
DEBUGdetailed tracing.INFOnormal progress.WARNINGsomething odd but recoverable.ERRORan operation failed.CRITICALthe 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.
AI チューターと学ぶ Python — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「Bot のロギングとエラーハンドリング」レッスンは無料ですか?
はい。「Bot のロギングとエラーハンドリング」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web Scraping & Botsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web Scraping & Botsコースには全4レッスンが含まれています。
「Bot のロギングとエラーハンドリング」で何を学びますか?
構造化ロギングとグレースフルなエラーハンドリングを追加し、障害を把握して復旧できる、堅牢なシンプル Bot を構築します。 ブラウザで直接実行するハンズオンコードでWeb Scraping & Botsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Web Scraping & Botsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWeb Scraping & Botsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「Bot のロギングとエラーハンドリング」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWeb Scraping & Botsレッスンでコードを書いて実行できますか?
はい。すべてのWeb Scraping & Botsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- ボットの目的定義
- 単純なフォーム送信の自動化
- 基本タスクのスケジューリング
- Bot のロギングとエラーハンドリング