【发布时间】:2009-06-27 21:54:25
【问题描述】:
我想用 ruby 做一个日志文件解析器,这个解析器应该在它增长的时候解析日志文件。它应该逐行解析直到最后,然后等待(不知何故?)更多的行来,所以我的问题是如何最好地处理它的增长?
编辑: 即使我的日志文件在 Windows 上(目前),我也会更喜欢一种可移植的方式。
【问题讨论】:
我想用 ruby 做一个日志文件解析器,这个解析器应该在它增长的时候解析日志文件。它应该逐行解析直到最后,然后等待(不知何故?)更多的行来,所以我的问题是如何最好地处理它的增长?
编辑: 即使我的日志文件在 Windows 上(目前),我也会更喜欢一种可移植的方式。
【问题讨论】:
对于 Windows,您可以使用 Directory Change Notifications。您告诉 Windows(使用FindFirstChangeNotification)监视目录 c:/foo/logs,然后当该目录中发生某些事情时,Windows 会更新您的句柄。此时,您检查更改是否涉及您关心的文件。
Ruby 绑定了 Win32 API,并且有an example 可以获取这些通知。
【讨论】:
http://www.biterscripting.com/SS_WebLogParser.html 发布了一个很好的脚本。它是为 Web 服务器日志编写的示例脚本,但可以用作为任何类型的日志编写自己的日志解析器的起点。要在日志文件不断增长的同时连续使用它,这里有一个脚本。
# Script LogParser.txt
# Go in a continuous loop, sleeping 1 hr each time.
while (true)
do
# The number of lines in the log file the last time we checked is in following
# variable. Initially, it will be 0.
var int lines_old
# Read the log file into a str variable.
var str log ; cat "file.log" > $log
# Get the number of lines found this time.
var str lines_new ; set $lines_new = { len -e $log }
# Strip off the first $lines lines.
lex -e (makestr(int($lines))+"]") $log > null
# The new lines are now available in $log. Process them with something similar to
# SS_WebLogParser script.
# Update $lines_old, then, sleep.
set $lines_old = $lines_new
sleep 3600 # 3600 seconds = 1 hour
done
试一试,
通过输入以下命令调用我们的脚本。
脚本“\LogParser.txt”
如果您需要使用他们的任何示例脚本,请使用以下命令安装它们。
script "http://www.biterscripting.com/Download/SS_AllSamples.txt"
帕特里克
【讨论】:
对于这个任务,您可以使用 IO.popen 在管道上获取命令行增长结果的文件流。然后在while循环中使用readline函数。 这是一个使用“adb logcat”命令获取 Android 设备实时增长日志的示例:
#! /usr/bin/env ruby
IO.popen("adb logcat") do |io|
while line = io.readline
line.strip!
# Process here
print "#{line}\n"
end
end
编辑
对于一个文件,它有点不同。我会“readline”轮询文件流。
#! /usr/bin/env ruby
File.open("test.log") do |io|
loop do
begin
line = io.readline
line.strip!
rescue
sleep 0.2
retry
end
# Process here
print "#{line}\n"
end
end
【讨论】: