855 views
Linux-shell脚本

Nginx日志处理

一、日志切割脚本

将下面的脚本加入到crontab中,每小时执行一次

[code]

#!/bin/bash

#auto mv nginx log shell

#by ying

S_LOG=/usr/local/nginx/logs/access.log

D_LOG=/data/backup/`date +%Y%m%d`

echo -e “\033[32mPlease wait 2s start cut shell scripts…\033[1m”

sleep 2

if [ ! -d $D_LOG ];then

mkdir -p $D_LOG

fi

mv $S_LOG $D_LOG

kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`

echo “——————————————-”

echo “The Nginx log Cutting Successfully!”

echo “You can access backup nginx log $D_LOG/access.log files.”

[/code]

二、分析Nginx日志,统计网站的IP、UV、PV及早上9点-10点的访问排前20的URL,并将IP和URL均打印出来;

IP:表示独立IP访问数,一个IP记为一IP,即使该IP下有很多用户也记为1个

UV: 表示独立用户访问数,一个用户为一个UV,一般通过cookie记录用户唯一标示符(一个UV可以产生多个PV)

PV: 表示页面访问数,只要刷新一次页面PV+1

IP统计:awk ‘{print $1}’ access.log |sort | uniq -c |wc -l

UV统计:awk ‘{print $1}’ access.log |sort | uniq -c |wc -l

PV统计:awk ‘{print $7}’ access.log |wc -l

早上9点-10点的访问排前20的URL,并将IP和URL均打印出来:

sed -n ‘/04\/Aug\/2017\:09\:00/,/04\/Aug\/2017\:10\:00/p’ access.log |awk ‘{print $11}’ |sort |uniq -c|sort -n -k 1 -r|sed -n ‘1,20p’ 》》》》URL

sed -n ‘/04\/Aug\/2017\:09\:00/,/04\/Aug\/2017\:10\:00/p’ access.log |awk ‘{print $1″—“$11}’ |sort |uniq -c|sort -n -k 1 -r|sed -n ‘1,20p’ 》》》》URL+IP

三、自动每天统计Nginx日志,打印访问时间大于5秒的URL,并且把相关信息通过WEB表格线上展示出来,通过浏览器可以访问该数据

截取log中访问时间大于5s的URL跟IP 等信息:cat access.log |awk ‘($NF>5){print $1″|”$9″|”$11″|”$4″|”$NF}’|sed ‘s/\[//g’ > 1.txt

对1.txt进行格式转换的脚本

[code]

#!/bin/sh

#2017年9月8日11:17:52

#by ying

#nginx log web

file_input=’1.txt’

file_output=’index.html’

td_str=”

function create_html_head(){

echo -e “<html>

<body>

<h1>Nginx日志分析表</h1>”

}

function create_table_head(){

echo -e “<table border=”1″>

<tr><th>客户端IP</th>

<th>访问状态码</th>

<th>访问URL</th>

<th>访问时间</th>

<th>延时</th>

<th>备注</th>”

}

function create_tr(){

create_td “$1”

echo -e “<tr>

$td_str

</tr>” >> $file_output

}

#create_tr

function create_td(){

echo $1

td_str=`echo $1 | awk ‘BEGIN{FS=”|”}”{i=1; while(i<=NF) {print “<td>”$i”</td>”;i++}}’`

echo $td_str

}

function create_table_end(){

echo -e “</table>”

}

function create_html_end(){

echo -e “</body></html>”

}

function create_html(){

rm -rf $file_output

touch $file_output

create_html_head >> $file_output

create_table_head >> $file_output

while read line

do

echo $line

create_tr “$line”

done < $file_input

create_table_end >> $file_output

create_html_end >> $file_output

}

create_html

[/code]

效果图!!!!!

Leave a Reply

影子专属博客 赣ICP备17013143号