Real-time Monitoring log files

Source: Internet
Author: User

A process is running and constantly writing logs. You need to monitor log file updates in real time (usually used in debug). What should you do? Keep opening and closing files? No. There are at least two methods from two frequently-used commands:

  1. Tail-F log.txt, another process is writing logs, and you can use tail to print new content in real time.
  2. Less log.txt. If you want to monitor updates, press F. If you want to suspend monitoring, press Ctrl + C to view the updates on pages up and down. If you want to continue monitoring, press F. This function is more powerful than tail.

It is easy to simulate:

  1. Continuously update files in a shell:
     $ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
  2. In another shell, tail-F log.txt or less log.txt

 

Writing a program similar to tail is actually quite simple:

# Notices:# 1. the 3rd parameter of open() is to disable file buffering#      so file updated by another process could be picked up correctly#      but since your focus is newly added tail, enable buffering is ok too# 2. It is not necessary to fh.tell() to save the position, and then seek()#     to resume, as if readline() failed, the pointer stay still at the EOFimport sysimport timefilename = sys.argv[1]with open(filename, ‘r‘, 0) as fh:    while True:        line = fh.readline()        if not line:            time.sleep(1)        else:            print line

This can be used as a good interview question.

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.