Last active
August 30, 2017 10:16
-
-
Save mattn/c35519b995660a83ecb69299738bc1b9 to your computer and use it in GitHub Desktop.
nginx のアクセスログからIP毎のアクセス回数(ステータス400以上)を表示するコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"strconv" | |
"time" | |
"github.com/satyrius/gonx" | |
) | |
func main() { | |
acc := make(map[string]int) | |
f, err := os.Open("/var/log/nginx/access.log") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer f.Close() | |
reader := gonx.NewReader(f, `$remote_addr - - [$time_local] "$request" $status`) | |
for { | |
rec, err := reader.Read() | |
if err == io.EOF { | |
break | |
} else if err != nil { | |
panic(err) | |
} | |
addr, err := rec.Field("remote_addr") | |
if err != nil { | |
continue | |
} | |
tlocal, err := rec.Field("time_local") | |
if err != nil { | |
continue | |
} | |
t, err := time.Parse(`02/Jan/2006:15:04:05 -0700`, tlocal) | |
if err != nil { | |
continue | |
} | |
status, err := rec.Field("status") | |
if err != nil { | |
continue | |
} | |
ns, err := strconv.ParseInt(status, 10, 64) | |
if err != nil { | |
continue | |
} | |
if ns >= 400 { | |
println(t.String()) | |
if _, ok := acc[addr]; ok { | |
acc[addr] += 1 | |
} else { | |
acc[addr] = 1 | |
} | |
} | |
} | |
fmt.Println(acc) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment