Skip to content

Instantly share code, notes, and snippets.

@mattn
Last active August 30, 2017 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattn/c35519b995660a83ecb69299738bc1b9 to your computer and use it in GitHub Desktop.
Save mattn/c35519b995660a83ecb69299738bc1b9 to your computer and use it in GitHub Desktop.
nginx のアクセスログからIP毎のアクセス回数(ステータス400以上)を表示するコード
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