Python 记录日志报警的方式

Python 标准库中,可以列举出如下常见场景日志报警解决方案:


方案 1:简单日志告警(推荐基础方案)

import logging

def send_alert(message):
    logging.error(f"ALERT: {message}")
    # 可扩展:同时写入文件/发送到日志服务器

# 配置日志格式
logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

无需额外安装包,适合本地开发或简单场景


方案 2:邮件告警(需 SMTP 服务)

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
SMTP_USER=alert@example.com
SMTP_PASSWORD=your_email_password
ALERT_EMAIL_FROM=alert@example.com
ALERT_EMAIL_TO=devops@example.com

方案 3:Slack 通知(推荐团队协作)

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
🔧 配置步骤

  1. 在 Slack 创建 Incoming Webhook
  2. .env 添加:
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXX/YYYY

方案 4:桌面弹窗通知(适合本地开发)

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

最佳实践建议

  1. 多通道组合

    def send_alert(message):
        logging.error(message)          # 基础日志
        send_to_slack_async(message)    # 异步非阻塞通知团队
    
  2. 异步处理
    使用 threading 避免阻塞主程序:

    import threading
    
    def async_alert(message):
        threading.Thread(target=send_alert, args=(message,)).start()
    
  3. 敏感信息加密
    对邮件/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团队协作环境
桌面弹窗本地开发环境
组合方案关键业务系统最高

根据实际需求选择,建议至少实现日志告警 + 一种主动通知方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值