Example of python dynamic monitoring log content

Source: Internet
Author: User
This article describes how to use the Python Dynamic Monitor program log content. the dynamic here refers to the constant addition of new log content to log files, dynamic Monitoring refers to the monitoring log new append log content log files are generally generated by day, by judging the file generation date and the current time in the program, change the monitoring log file
The program is just a simple example, monitoring test1.log 10 seconds, to monitoring test2.log

Program monitoring uses the linux command tail-f to dynamically monitor new append logs

The code is as follows:


#! /Usr/bin/python
# Encoding = UTF-8
# Filename: monitorLog. py
Import OS
Import signal
Import subprocess
Import time


LogFile1 = "test1.log"
LogFile2 = 'test2. log'

# Log files are generally generated on a daily basis. The program judges the file generation date and current time and replaces the monitored log files.
# The program is just a simple example, monitoring test1.log for 10 seconds, turning to monitoring test2.log
Def monitorLog (logFile ):
Print 'monitoring log file is % s' % logFile
# The program runs for 10 seconds and monitors another log
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 ()
# Determine whether the content is empty
If line:
Print (line)
# Current time
Thistime = time. strftime ('% Y-% m-% d % H: % M: % s', time. localtime (time. time ()))
If thistime> = stoptime:
# Killing sub-processes
Popen. kill ()
Print 'kill subprocess'
Break
Time. sleep (2)
MonitorLog (logFile2)

If _ name _ = '_ main __':
MonitorLog (logFile1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.