Monitor a log file using tail -f

2019-09-22 05:39发布

问题:

Need some guidance

Monitor a application log file(log rotation is daily)using tail-f, if exception in log file need to send alert using script.

回答1:

It's hard to build a log monitor with just tail -f. tail does have a +c option to read from a particular position, but it would be tricky to build good code around it.

What you need is this:

  • a read control file that stores the last byte position read from the log file
  • a script that uses the read control file to do incremental reads (using seek) and does pattern matching and notification based on the lines read, and updates the read control file
  • the inode number could be used for naming the read control file so that the incremental logic continues to work even if the log file is renamed or moved

The above script could either run as a daemon or execute periodically as a cron job. I would strongly suggest using Perl, Ruby, Python, or even Java/C/C++ for this.