温馨提示×

如何编写有效的Ubuntu日志监控脚本

小樊
73
2025-06-30 21:50:04
栏目: 智能运维

编写一个有效的Ubuntu日志监控脚本可以帮助你实时监控系统日志,及时发现和解决问题。以下是一个简单的Python脚本示例,使用tail -f命令来实时监控日志文件,并使用subprocess模块来执行命令。

import subprocess
import time

def monitor_log(log_file):
    # 使用tail -f命令实时监控日志文件
    command = ["tail", "-f", log_file]
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    try:
        while True:
            line = process.stdout.readline()
            if line:
                print(line.strip())  # 打印新的一行日志
            time.sleep(0.1)  # 稍微休眠一下,避免CPU占用过高
    except KeyboardInterrupt:
        print("停止监控")
        process.terminate()

if __name__ == "__main__":
    log_file = "/var/log/syslog"  # 你可以根据需要修改日志文件路径
    monitor_log(log_file)

解释

  1. 导入模块

    • subprocess:用于执行外部命令。
    • time:用于控制循环的休眠时间。
  2. 定义monitor_log函数

    • 使用subprocess.Popen执行tail -f命令,实时监控指定的日志文件。
    • stdout=subprocess.PIPEstderr=subprocess.PIPE将标准输出和标准错误重定向到管道,以便我们可以读取它们。
    • text=True参数确保输出是文本格式,而不是字节格式。
  3. 循环读取日志

    • 在无限循环中,使用process.stdout.readline()读取新的一行日志。
    • 如果读取到新的一行日志,打印出来。
    • 使用time.sleep(0.1)稍微休眠一下,避免CPU占用过高。
  4. 处理中断

    • 使用try...except KeyboardInterrupt捕获用户中断(例如按下Ctrl+C),并优雅地终止进程。
  5. 主程序

    • 指定要监控的日志文件路径(例如/var/log/syslog)。
    • 调用monitor_log函数开始监控。

注意事项

  • 确保你有权限读取指定的日志文件。
  • 根据需要修改日志文件路径。
  • 可以根据具体需求扩展脚本功能,例如添加日志级别过滤、发送警报等。

这个脚本是一个基础示例,可以根据实际需求进行扩展和优化。

0