172.16.1.1 - - [04/Feb/2015:23:40:01 +0800] "POST /api/message/query HTTP/1.1" 200 52 "-" "Apache-HttpClient/4.2 (java 1.5)" "-" "message.test.com" "172.16.3.159" "-" "0.116" "-" "0.116" "-" remote_addr_ac_logon
取出time、url、請求大小,sub(/\[/,"",$4)
去掉時間中的中括號,sub(/Feb/,"2",$4)
把Fed替換爲2 awk
的sub
函數用於替換字符串,語句單獨使用,若是使用賦值語句,如a=sub(/Feb/,"2",$4)
則a=1
,返回替換次數java
cat message-access.log | awk 'BEGIN {print "time,url,size"} {sub(/\[/,"",$4);sub(/Feb/,"2",$4);print $4","$7","$10}' > message-time.log
而後使用R語言導入這個文件,用ggplot2
畫圖,在R語言中經過使用ddply
函數作統計分組,ddply
的使用參見:ddply使用
但R語言作統計分組效率較低,文件大小在1G以上的時候,內存壓力很大,這時使用uniq
或awk
作分組比較合適nginx
sort
和uniq
統計分組統計每秒請求數,並使用sed去年最終結果中的每行開頭的空格api
cat message-time.log | awk -F',' '{print $1}'| sort -rn | uniq -c | sed 's/^[][ ]*//g'> message-time-count.log
但uniq
只能統計出現次數,不能統計累加的值函數
awk
統計分組每分鐘請求數據包大小, group by time,sum(size),取time字段的前16個字符,去掉最後的秒:substr($1,0,16)
,在END語句中打印統計結果,把秒都置爲0url
cat message-time.log | awk -F"," '{a[substr($1,0,16)]+=$3}END{for(i in a) print i"0",a[i]}' > message-time-size.log
加載包spa
library(ggplot2)library(scales)
R語言讀取文件,as.is=TRUE
字符不轉factor
.net
message = read.csv('e:/R/message-time-size.log', as.is=TRUE, header=FALSE, sep = ",", col.names=c('time','size'))
轉爲時間類型日誌
message$time = as.POSIXlt(strptime(message$time,"%d/%m/%Y:%H:%M:%S"))
byte轉爲kbcode
message$size<- message$size / 1024
畫「時間-流量圖」,x軸每1小時顯示一個值,顯示格式只顯示小時orm
ggplot(message,aes(x=time,y=size)) + geom_line() + labs(title="時間-流量圖",y='size(KB)') + scale_x_datetime(breaks=date_breaks("1 hour"),labels= date_format("%H"))
保存圖片
ggsave(filename='e:/R/時間-流量圖-分.jpg',width=15,height=8)
統計url訪問次數圖
ggplot(message)+ geom_bar(aes(x=url)) + coord_flip() + labs(x='url',y='count')
餅狀圖
ggplot(message)+ geom_bar(aes(x=factor(1),fill=url)) + coord_polar(theta='y') + labs(x='',y='')ggsave(filename='e:/R/url-餅狀圖.jpg')