如何在 Linux 中每次 tail -f 显示日志文件中的新行时执行 mysql 查询
我正在尝试使用 tail -f 监视日志文件,解析它以使用 grep 提取一些数据并将数据作为 mysql 查询传递。 我可以通过将 tailf 检测到的每个新行传递给 php 脚本来做到这一点,但我不知道该怎么做。 或者我可以直接用php模拟tailf,但是如何用php监视文件的更改? 我想只要花点时间,寻找大小,记住最后的位置,寻找它并阅读直到差异,对吧? 任何人都可以提供一些关于什么更好使用的提示?或者更简单? 我还听说命名管道可能是一个解决方案,但不知道如何从那里获取数据 顺便说一下,记录器是 nginx.. 谢谢
I'm trying to monitor a log file with tail -f , parse it to extract some data with grep and pass the data as a mysql query.
I could do that by passing each new line detected by tailf to a php script, but I don't know how to do that..
Or i could simulate tailf with php directly, but how to I monitor a file for changes with php?
I think just by having a while , look for the size , remember the last position, seek it and read till the difference right?
Anyone can give some hints on what's better to use? or simpler?
Also i've heard named pipes could be a solution but don't know how to grab the data from there
The logger is nginx by the way..
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 shell 中,您可以执行以下操作:
只需将
echo $line
行更改为您想要的内容 - 您可以调用 PHP 或该行中您想要的任何内容,$line
是来自 tail/grep 组合的行。查看这些 SOq 以获取更多信息:
In shell you can do something like:
Just change the line
echo $line
to what you want - you can call PHP or whatever you want in that line,$line
is the the line from tail/grep combination.Take a look at these SOq for more info:
你正在混合不同的方法。 tail -f 意味着您将有一个进程一直运行,如果日志文件被截断(旋转),您很可能会陷入困境。如果你需要好的日志监控功能(我假设是linux),那么你必须监控文件的更改并寻找记住的位置。恕我直言,最好的方法是依赖现有的解决方案。 syslog-ng 似乎首先浮现在脑海中。它可以将您的日志文件通过管道传输到您的程序中。但非系统日志的情况并非如此。我会选择 http://www.php.net/manual/en/ intro.inotify.php。这将需要一个正在运行的进程。作为最终(顺序取决于您的情况)解决方案,我将使用 cron 进行定期检查。
you are mixing to different approaches. tail -f means you will have a process running all the time and if the log file is truncated (rotated) you will most probably get stuck. If you need good thing for log monitoring (i assume linux) then you have to monitor the file for changes and seek to the remembered position. The IMHO best way is to rely on an existing solution. syslog-ng seems to come firs to to mind. It can pipe your log files into your program. Though not the case with non sysloged logs. The I would opt for http://www.php.net/manual/en/intro.inotify.php. This will require a running process. As the final (the order depends on your situation) solution I would go for a periodic checking with cron.