python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python记录日志报警

Python记录日志报警详解

作者:Tipriest_

Python日志报警方案包括简单日志、邮件(需SMTP)、Slack(需requests)、桌面弹窗(需plyer),推荐基础方案用于本地开发,多通道组合提升可靠性,异步处理避免阻塞,敏感信息加密存储,根据场景选择,建议至少实现日志告警+主动通知方式

在 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

配置步骤

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

最佳实践建议

多通道组合

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团队协作环境
桌面弹窗本地开发环境
组合方案关键业务系统最高

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文