Python实现日志备份守护进程的示例!
Python实现日志备份守护进程的示例!
作者:漫谈网络
本文主要介绍了Python实现日志备份守护进程的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
实训背景
假设你是一名运维工程师,需要为公司的监控系统开发一个简单的日志备份守护进程。该进程需满足以下需求:
- 后台运行:脱离终端,长期监控指定目录(如 /var/log/app/)中的日志文件。
- 自动备份:每隔 5 分钟将新增的日志文件压缩备份到 /backup/logs/ 目录。
- 日志记录:记录守护进程自身的操作日志到 /var/log/backup_daemon.log。
- 系统服务化:通过 systemd 管理进程的启动、停止和状态查看。
环境准备
操作系统:Ubuntu/CentOS 等主流 Linux 发行版
Python 版本:Python 3.x
依赖安装:
1
2
3
|
# 确保已安装 Python3 和 pip sudo apt install python3 python3-pip # Ubuntu sudo yum install python3 python3-pip # CentOS |
实训步骤
任务1:编写 Python 守护进程代码
目标:用 Python 实现日志监控与备份逻辑,无需手动处理 fork()
。
创建脚本 backup_daemon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import os import time import logging from datetime import datetime import subprocess # 配置日志 logging.basicConfig( filename = '/var/log/backup_daemon.log' , level = logging.INFO, format = '%(asctime)s - %(message)s' , datefmt = '%Y-%m-%d %H:%M:%S' ) def backup_logs(): log_dir = '/var/log/app' backup_dir = '/backup/logs' # 遍历日志目录 for root, _, files in os.walk(log_dir): for file in files: src_path = os.path.join(root, file ) dest_path = os.path.join(backup_dir, f "{file}.tar.gz" ) # 检查是否已备份 if not os.path.exists(dest_path): logging.info(f "Backing up {file}..." ) # 使用 tar 压缩 try : subprocess.run( [ 'tar' , '-czf' , dest_path, src_path], check = True , stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL ) except subprocess.CalledProcessError as e: logging.error(f "Failed to backup {file}: {e}" ) if __name__ = = "__main__" : logging.info( "Daemon started." ) while True : backup_logs() time.sleep( 300 ) # 5分钟执行一次 |
任务2:配置 systemd 服务
目标:让 Python 脚本以服务形式在后台运行,无需代码内守护进程逻辑。
创建服务文件
1
|
sudo vim /etc/systemd/system/backup_daemon .service |
编写服务配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[Unit] Description=Python Log Backup Daemon After=network.target [Service] Type=simple ExecStart=/usr/bin/python3 /path/to/backup_daemon.py # 修改为实际脚本路径 Restart=on-failure RestartSec=5s User=root WorkingDirectory=/ # 可选:设置工作目录 [Install] WantedBy=multi-user.target |
部署并启动服务
1
2
3
|
sudo systemctl daemon-reload sudo systemctl start backup_daemon sudo systemctl enable backup_daemon |
任务3:测试与验证
生成测试日志文件
1
|
sudo touch /var/log/app/test .log |
查看备份结果
1
|
ls /backup/logs # 5分钟后应生成 test.log.tar.gz |
查看守护进程日志
1
|
tail -f /var/log/backup_daemon .log |
任务4:管理服务
查看状态
1
|
systemctl status backup_daemon |
停止服务
1
|
sudo systemctl stop backup_daemon |
查看 systemd 日志
1
|
journalctl -u backup_daemon -f # 实时跟踪日志 |
实训总结
通过本案例,您将掌握:
- 使用 Python 实现守护进程逻辑(无需手动
fork()
)。 - 通过
systemd
管理 Python 脚本的后台运行。 - 利用 Python 的
logging
模块记录操作日志。
知识要点
Python 优势:
- 无需处理底层
fork()
和setsid()
,代码更简洁。 - 使用
subprocess
模块可轻松调用系统命令(如tar
)。
systemd 管理:
- 通过
Type=simple
直接运行前台程序,systemd
自动守护化。 - 日志可通过
journalctl
统一查看。
日志记录:
- Python 内置
logging
模块提供灵活的日志管理。
扩展优化建议
- 增量备份:记录已备份的文件名或时间戳,避免重复压缩。
- 异常处理:增加
try/except
捕获文件操作异常。 - 配置文件:使用
configparser
模块管理路径、间隔时间等参数。
到此这篇关于Python实现日志备份守护进程的示例的文章就介绍到这了。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。