Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
executable file 71 lines (57 sloc) 1.35 KB
#!/usr/bin/env ruby
# frozen_string_literal: true
# vbnla: Very basic nginx log analysis.
# Feed it a standard nginx access.log on stdin.
require "json"
VBNLA_CONFIG = File.expand_path "~/.config/vbnla"
IGNORE_PATTERNS = if File.exist?(VBNLA_CONFIG)
File.readlines(VBNLA_CONFIG).map(&:chomp!)
else
[]
end
LOGFORMAT = /
(?<ip>.+)
\s
-
\s
(?<user>.+)
\s
\[(?<time>.+)\]
\s
"(?<method>\S+)\s(?<req>\S+)\s(?<proto>\S+)"
\s
(?<stat>\d{3})
\s
(?<size>\d+)
\s
"(?<ref>.*)"
\s
"(?<ua>.*)"
/x.freeze
N = ENV.fetch("N", 10).to_i
def topn_pretty(hist)
hist.to_a.max_by(N, &:last).map { |e| "#{e[0]} -> #{e[1]}" }.join("\n\t")
end
hist = Hash.new { |hash, key| hash[key] = Hash.new(0) }
lines = 1
$stdin.each_line do |line|
lines += 1
hsh = LOGFORMAT.match(line).named_captures rescue next
hsh.each do |k, v|
hist[k][v] += 1
end
end
# Filter out any request paths that match IGNORE_PATTERNS.
hist["req"].reject! { |req| IGNORE_PATTERNS.any? { |pat| File.fnmatch?(pat, req) } }
puts <<~SUMMARY
Total requests: #{lines}
Unique IPs: #{hist["ip"].size}
Top #{N} IPs:
\t#{topn_pretty hist["ip"]}
Top #{N} UAs:
\t#{topn_pretty hist["ua"]}
Top #{N} requests:
\t#{topn_pretty hist["req"]}
Top #{N} referrers:
\t#{topn_pretty hist["ref"]}
SUMMARY