简体   繁体   English

使用 Logstash 管道计算日志中的行号

[英]Calculate Line Number in Log with Logstash Pipeline

Imagine that have some logs like this想象一下有一些这样的日志

Jun2012|16:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|
Jun2012|17:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|
Jun2013|16:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|
Jun2012|18:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|
Jun2012|19:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|

..... I can see the line number in an editor but I want to calculate line number of each line and make field of it.In out put inside a json like .....我可以在编辑器中看到行号,但我想计算每行的行号并制作它的字段。在 json 中输出

{...,"line_num" : 23, ...} 

How can i make this?我怎么能做这个? Can someone give an example?有人可以举个例子吗?

Ruby has a special variable $. Ruby 有一个特殊的变量$. that has the line number.有行号。

File.foreach(logfile).each do |line|
   puts "#{$.}: #{line}"
end

Try the below with readlines and with_index使用readlineswith_index尝试以下操作

result = []
File.readlines('test.log').each.with_index(1) do |line, index|
  result << { content: line, line_num: index }
end

Output: Output:

2.6.3 :042 > pp result
[{:content=>
   "Jun2012|16:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|\n",
  :line_num=>1},
 {:content=>
   "Jun2012|17:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|\n",
  :line_num=>2},
 {:content=>
   "Jun2013|16:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|\n",
  :line_num=>3},
 {:content=>
   "Jun2012|18:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|\n",
  :line_num=>4},
 {:content=>
   "Jun2012|19:52:39|10.0.0.1|log|keyinst||daemon|inbound|VPN-1 & FireWall-1|Certificate initialized|",
  :line_num=>5}]

Logstash has no information about the line number of the event in a file, and it only tracks the byte offset when you use the file input. Logstash 没有关于文件中事件行号的信息,它仅在您使用file输入时跟踪字节偏移量。

If you are using filebeat to ship your logs to logstash you also have the information about the byte offset, but there is no tracking of the actual line number.如果您使用 filebeat 将日志发送到 logstash,您还可以获得有关字节偏移量的信息,但不会跟踪实际行号。

If you want to just order your events you can use this offset, if you need the actual line number you will need to implement a way to add this information in your event before sending it to logstash.如果您只想订购您的事件,您可以使用此偏移量,如果您需要实际的行号,则需要实现一种方法来在您的事件中添加此信息,然后再将其发送到 logstash。

I have solved that issue, with creating your own input codec plugin you can calculate line numbers via iterating over events我已经解决了这个问题,通过创建自己的输入编解码器插件,您可以通过迭代事件来计算行号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM