“查看爬虫日志”要看你用的是哪种爬虫、部署在什么环境。下面按最常见场景给你一套通用做法,基本能覆盖 90% 的情况。
如果你是在本地运行:
python spider.py
日志通常直接打印在终端。
✅ 建议:用 logging 模块,而不是 print
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("爬虫启动")
logging.basicConfig(
filename="spider.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
查看日志:
cat spider.log
tail -f spider.log # 实时查看
grep ERROR spider.log
Scrapy 默认会输出日志到终端。
scrapy crawl myspider -s LOG_FILE=spider.log
或 settings.py:
LOG_FILE = "spider.log"
LOG_LEVEL = "INFO"
tail -f spider.log
grep ERROR spider.log
docker ps
docker logs <container_id>
docker logs -f <container_id> # 实时
进容器:
docker exec -it <container_id> bash
cat /app/spider.log
nohup python spider.py > spider.log 2>&1 &
查看:
tail -f spider.log
cron 不会自动显示日志,需要手动重定向:
0 8 * * * /usr/bin/python /path/spider.py >> /path/spider.log 2>&1
查看:
tail -f /path/spider.log
| 需求 | 命令 |
|---|---|
| 实时查看 | tail -f spider.log |
| 只看错误 | grep ERROR spider.log |
| 查看最后 100 行 | tail -n 100 spider.log |
| 分页查看 | less spider.log |
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.FileHandler("spider.log")
handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
)
logger.addHandler(handler)
你可以直接告诉我:
我可以给你完全针对你环境的查看方案。