LoginSignup
2
4

More than 5 years have passed since last update.

apacheのアクセスログ解析

Posted at

コピペ用

ログローテーションされたファイルを結合して、ステータスコード別の行数を表示する

ls access_log-201704* | xargs cat | cut -f 9 -d ' ' | sort | uniq -c

アクセスログ解析で使えるコマンド

catでファイルを結合する

こうやって書くと、file1とfile2を結合できる

cat file1 file2 

例)

$ echo 123 > file1
$ echo 456 > file2
$ cat file1 file2
#=>
123
456

複数ファイルを一気に指定したい時は、xargsが使える。
xargsはパイプで受け取った値をコマンドの引数として渡せる。

$ echo 123 > file1
$ echo 456 > file2
$ ls file* | xargs cat
#=>
123
456

ステータスコード毎の行数を出力する

  1. cutコマンドでステータスコードだけ取り出す
  2. sortコマンドでソートする(uniqコマンドのため)
  3. uniqでステータス毎の行数を出力する

cutコマンドでステータスコードだけ取り出す

cutコマンドで行の中の一部分をとり出せる。
今回は、半角スペースで分割してステータスコードの部分を取り出す.

  • -d で分割する文字を指定する(指定しないとタブで分割する)
  • -f で分割した何番目のフィールドを取り出すかを指定する
$ echo "a b c" | cut -f1 -d ' '
#=>a
$ echo "a b c" | cut -f2 -d ' '
#=>b
$ echo "a b c" | cut -f3 -d ' '
#=>c

アクセスログからステータスを取り出す

$ cat access_log | cut -f9 -d ' '
#=>
200
200
200
401
200
500

sortコマンドでソートする(uniqコマンドのため)

sortしてくれる。

$ echo "3" > sort.txt
$ echo "1" >> sort.txt
$ echo "2" >> sort.txt
$ cat sort.txt
3
1
2

$ cat sort.txt | sort
1
2
3

uniqでステータス毎の行数を出力する

重複した削除して、重複をなくすことができる。 -c を指定すると重複してた数を表示してくれる。
ソートした文字列じゃないと上手く重複してくれない。

$ echo "a" > uniq.txt
$ echo "a" >> uniq.txt
$ echo "b" >> uniq.txt
$ cat uniq.txt
#=>
a
a
b
$ cat uniq.txt | uniq -c
#=>
   2 a
   1 b

組み合わせる

ls access_log-201704* | xargs cat | cut -f 9 -d ' ' | sort | uniq -c
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4