永发信息网

python怎么实现远程动态输出日志

答案:1  悬赏:30  手机版
解决时间 2021-01-23 10:44
  • 提问者网友:原来太熟悉了会陌生
  • 2021-01-23 05:37
python怎么实现远程动态输出日志
最佳答案
  • 五星知识达人网友:平生事
  • 2021-01-23 06:43
#!/usr/bin/python
# encoding=utf-8
# Filename: monitorLog.py
import os
import signal
import subprocess
import time


logFile1 = "test1.log"
logFile2 = 'test2.log'

#日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件
#程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log
def monitorLog(logFile):
    print '监控的日志文件 是%s' % logFile
    # 程序运行10秒,监控另一个日志
    stoptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + 10))
    popen = subprocess.Popen('tail -f ' + logFile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    pid = popen.pid
    print('Popen.pid:' + str(pid))
    while True:
        line = popen.stdout.readline().strip()
        # 判断内容是否为空
        if line:
            print(line)
        # 当前时间
        thistime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        if thistime >= stoptime:
            # 终止子进程
            popen.kill()
            print '杀死subprocess'
            break
    time.sleep(2)
    monitorLog(logFile2)

if __name__ == '__main__':
    monitorLog(logFile1)
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯