在 Python 标准库
中,可以列举出如下常见场景日志报警解决方案:
import logging
def send_alert(message):
logging.error(f"ALERT: {message}")
# 可扩展:同时写入文件/发送到日志服务器
# 配置日志格式
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s'
)
✅ 无需额外安装包,适合本地开发或简单场景
import smtplib
from email.mime.text import MIMEText
from os import getenv
def send_alert(message):
msg = MIMEText(message)
msg["Subject"] = "API Key 异常告警"
msg["From"] = getenv("ALERT_EMAIL_FROM") # 从.env读取
msg["To"] = getenv("ALERT_EMAIL_TO")
with smtplib.SMTP_SSL(getenv("SMTP_SERVER"), 465) as server:
server.login(getenv("SMTP_USER"), getenv("SMTP_PASSWORD"))
server.send_message(msg)
依赖包:Python 内置 smtplib
+ email
需在 .env
中配置:
SMTP_SERVER=smtp.example.com
[email protected]
SMTP_PASSWORD=your_email_password
[email protected]
[email protected]
import requests
from os import getenv
def send_alert(message):
webhook_url = getenv("SLACK_WEBHOOK_URL")
payload = {"text": f"⚠️ 告警: {message}"}
requests.post(webhook_url, json=payload)
依赖包:需安装 requests
配置步骤:
.env
添加:SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXX/YYYY
from plyer import notification
import sys
def send_alert(message):
if sys.platform in ["win32", "darwin", "linux"]:
notification.notify(
title="密钥异常",
message=message,
app_icon=None,
timeout=10
)
️ 依赖包:需安装 plyer
pip install plyer
多通道组合
def send_alert(message):
logging.error(message) # 基础日志
send_to_slack_async(message) # 异步非阻塞通知团队
异步处理
使用 threading
避免阻塞主程序:
import threading
def async_alert(message):
threading.Thread(target=send_alert, args=(message,)).start()
敏感信息加密
对邮件/Slack 的凭据使用加密存储:
from cryptography.fernet import Fernet
# 加密
cipher = Fernet(key)
encrypted = cipher.encrypt(b"secret_password")
# 解密
cipher.decrypt(encrypted)
import os
import logging
from dotenv import load_dotenv
from threading import Thread
import requests
# 加载环境变量
load_dotenv()
# 配置日志
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def send_alert(message):
"""多通道告警"""
# 1. 本地日志
logging.error(message)
# 2. 异步Slack通知
def _slack_alert(msg):
try:
webhook = os.getenv("SLACK_WEBHOOK")
requests.post(webhook, json={"text": msg}, timeout=3)
except Exception as e:
logging.error(f"Slack通知失败: {str(e)}")
Thread(target=_slack_alert, args=(message,)).start()
# 使用示例
try:
api_key = os.environ["API_KEY"]
except KeyError:
send_alert("API_KEY 缺失!立即更新.env文件!")
方案 | 适用场景 | 可靠性 | 复杂度 |
---|---|---|---|
日志 | 开发环境/简单生产环境 | 高 | 低 |
邮件 | 需要邮件通知的生产环境 | 中 | 中 |
Slack | 团队协作环境 | 高 | 中 |
桌面弹窗 | 本地开发环境 | 低 | 低 |
组合方案 | 关键业务系统 | 最高 | 高 |
根据实际需求选择,建议至少实现日志告警 + 一种主动通知方式。