如何在node.js中关注(不断变化的)日志文件 [英] How to follow a (changing) log file in node.js
问题描述
好的,这似乎是一个简单的问题,但我无法从此处找到答案,因此我将其发布,希望有人可能遇到了类似的问题.
OK this might appear to be an easy question but I couldn't find the answer from here so I am posting it in hope someone might have encountered the similar problem.
由于/var/log/lighttpd/error.log更具体) > Linus G Thiel 我弄清楚了跟随符号链接).我知道我可以设置fs.fileWatch
来监视它,但是我还应该指出,error.log
文件在特定的时间也会旋转,这取决于日志守护程序的设置.发生这种情况时,fs.fileWatch
停止工作.我也知道我可以产生一个子进程并运行
I need to monitor a symlink which points to a web server file (/var/log/lighttpd/error.log
to be more specific, thanks to Linus G Thiel I figured out how to follow symlinks). I know I can set up fs.fileWatch
to monitor it but I should also point out that the error.log
file also got rotated at a specific time, depending on whatever the log daemon settings are. When that happens, fs.fileWatch
stops working. I also know I can spawn a child process and run
tail -F ./symlink_to_error.log
从节点解决由日志轮换引起的问题,但是我更喜欢使用本机节点功能.任何人都可以对此有所了解吗?
from node to work around the problem caused by log rotation, but I prefer to use native node functions. Anyone can shed some light on this?
即使日志文件旋转了,实际监视实际的日志文件也可以正常工作.该问题实际上是由符号链接引起的.我监视符号链接的原因是,当大小达到特定限制时,实际的日志文件名会更改.仅以/var/log/lighttpd/error.log
为例.我无法控制日志文件的重命名方式,但是我有一个crontab,它每分钟更新一次符号链接,从而更新符号链接.
Actually monitoring the actual log file works without any problem, even when the log file got rotated. The problem is actually caused by the symlink. The reason I am monitoring the symlink is because the actual log file name gets changed when the size reaches certain limit. /var/log/lighttpd/error.log
is just given as an example. I have no control over how the log file is renamed but I do have a crontab that updates the symlink every minute that updates the symlink.
实际上,我正在使用以下方法(通过生成)
Actually I am using the following method (through spawn)
tail -F ./symlink_to_error.log
在我正在从事的日志监视项目中,尽管它的工作效率不如watchFile()高效,但事件确实可靠.
in a log monitoring project that I am working on as it works quite reliably event though it's not as efficient as watchFile().
推荐答案
除了观看符号链接和/或其目标文件外,还要观看包含目标日志文件的目录并在"change"事件中检查是否日志文件已滚动到另一个名称.如果已安装,则在新的日志文件上设置新的文件监视程序.
In addition to watching the symlink and/or its target file, watch the directory that contains the target log file and on the "change" event check to see if the log file has rolled to a different name. If it has then setup a new file watcher on the new log file.
fs.watchFile(logDir, function(curr, prev) {
if (curr.nlink != prev.nlink) {
// The number of links in the directory has changed, now
// see if there is a new log file and start watching it.
}
});
这篇关于如何在node.js中关注(不断变化的)日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!