当前位置: 首页 > news >正文

三、Python日志系统之监控邮件发送

import smtplib
from email.mime.text import MIMEText
import time
import os
import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler# 邮件配置
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_username@example.com'
SMTP_PASSWORD = 'your_password'
EMAIL_FROM = 'your_username@example.com'
EMAIL_TO = 'recipient@example.com'class LogFileHandler(FileSystemEventHandler):def __init__(self, log_file):self.log_file = log_filedef on_modified(self, event):if event.src_path == self.log_file and event.event_type == 'modified':with open(self.log_file, 'r') as f:lines = f.readlines()for line in lines:if "ERROR" in line:self.send_email(line.strip())def send_email(self, error_message):subject = 'Error Alert'body = f'Error message: {error_message}'msg = MIMEText(body)msg['Subject'] = subjectmsg['From'] = EMAIL_FROMmsg['To'] = EMAIL_TOtry:server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)server.starttls()server.login(SMTP_USERNAME, SMTP_PASSWORD)server.sendmail(EMAIL_FROM, [EMAIL_TO], msg.as_string())server.quit()print("Email notification sent successfully.")except Exception as e:print(f"Failed to send email notification: {e}")# 示例用法
if __name__ == "__main__":# 创建监控程序实例base_dir = os.path.dirname(os.path.abspath(__file__))log_dir = os.path.join(base_dir, "logs")log_file = datetime.datetime.now().strftime("%Y-%m-%d") + ".log"log_path = os.path.join(log_dir, log_file)if not os.path.exists(log_path):with open(log_path, 'w') as f:f.write("INFO: This is an info message.\n")f.write("WARNING: This is a warning message.\n")f.write("ERROR: This is an error message.\n")f.write("ERROR: Another error message.\n")f.write("INFO: Another info message.\n")observer = Observer()observer.schedule(LogFileHandler(log_path), os.path.dirname(log_path))observer.start()print(f"Started monitoring {log_path} for errors...")try:while True:time.sleep(1)except KeyboardInterrupt:observer.stop()observer.join()

邮件配置:

设置了 SMTP 服务器地址、端口、用户名、密码等信息,用于发送邮件。
send_email 方法:

当监控到含有 “ERROR” 字符串的日志行时,调用 send_email 方法发送邮件通知。
示例用法:

main 中启动监控程序,监听日志文件,并且每当发现含有 “ERROR” 的日志行时,发送邮件通知。
请确保将 SMTP_SERVER、SMTP_PORT、SMTP_USERNAME、SMTP_PASSWORD、EMAIL_FROM 和 EMAIL_TO 替换为你实际的邮件服务器和邮箱地址。这样,当日志文件被修改并包含错误消息时,你会收到邮件通知。

http://www.lryc.cn/news/395548.html

相关文章:

  • 16张支付牌照将到期,新规落地以来,支付牌照的首次续展。
  • VS2022 python 中文注释报错如何解决?
  • GitLab介绍,以及add an SSH key
  • 计算机视觉——opencv快速入门(二) 图像的基本操作
  • ViewPager
  • linux watchdog 子系统
  • 论文引用h指数
  • 四、Python日志系统之日志文件的备份和删除
  • Android Camera Framework:从基础到高级
  • 面向 Rust 新手的 Cargo 教程:轻松上手
  • MSPM0G3507——时钟配置(与32关系)
  • Linux 创建新虚拟机的全过程图解
  • 【已解决】腾讯云安装了redis,但是本地访问不到,连接不上
  • python批量去除图片文字水印
  • C++ Qt 自制开源科学计算器
  • 相机光学(二十八)——感光度(ISO)
  • 基于全国产复旦微JFM7K325T+ARM人工智能数据处理平台
  • HarmonyOS Next应用开发之系统概述
  • RedHat运维-Linux SSH基础2-基于公钥认证
  • 机器学习模型运用在机器人上
  • 振弦采集仪在大型工程安全监测中的作用与意义
  • CVE-2024-36991:Splunk Enterprise任意文件读取漏洞复现 [附POC]
  • Python的utils库详解
  • 基于 Qt、FFmpeg 和 OpenGL 开发跨平台安卓实时投屏软件 QtScrcpy
  • LabVIEW光谱测试系统
  • SpringBoot使用@RestController处理GET和POST请求
  • Kudu分区策略
  • spring的bean注册
  • 权限控制权限控制权限控制权限控制权限控制
  • JavaWeb系列二十一: 数据交换和异步请求(JSON, Ajax)