机器人日志记录与错误处理
通过添加结构化日志记录和优雅的错误处理,构建具有韧性的简单机器人,让故障可见且可恢复。
机器人日志记录与错误处理 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「机器人日志记录与错误处理」课时是免费的吗?
是的 — 「机器人日志记录与错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。
「机器人日志记录与错误处理」这节课中我会学到什么?
通过添加结构化日志记录和优雅的错误处理,构建具有韧性的简单机器人,让故障可见且可恢复。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Scraping & Bots 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「机器人日志记录与错误处理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Scraping & Bots 课中编写并运行代码吗?
能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。