日志分析工具Awstats實戰(zhàn)之Nginx篇:分析結(jié)果動態(tài)化
繼上一篇文章“分析工具Awstats實戰(zhàn)之Nginx篇-分析結(jié)果靜態(tài)化”后,作者推出了這個系列的第二篇:日志分析工具Awstats實戰(zhàn)之Nginx篇:分析結(jié)果動態(tài)化,介紹了如何將awstats的日志分析信息用靜態(tài)頁面來進行顯示,不過顯示效果肯定沒有動態(tài)的好,本篇文章將帶大家一起來部署動態(tài)的分析結(jié)果查閱。
環(huán)境:
- CentOS 6.4
- ip:192.168.1.113
- 域名:www.sunsky.com(server和client都通過hosts文件解析)
- nginx-1.2.9 編譯安裝,路徑/usr/local/nginx,服務(wù)開啟狀態(tài)
- 日志記錄格式為nginx默認(rèn)的,切勿更改,否則會造成awstats無法分析日志。
- log_format main '$remote_addr - $remote_user [$time_local] "$request" '
- '$status $body_bytes_sent "$http_referer" '
- '"$http_user_agent" "$http_x_forwarded_for"';
- awstats-7.2.tar.gz CPAN-2.00.tar.gz FCGI-0.74.tar.gz FCGI-ProcManager-0.24.tar.gz
- 必須有perl-devel,不然無法編譯FCGI。
一、日志自動切割
對于nginx的日志切割,由于沒有像apache一樣去用cronolog工具,這里我們就寫一個腳本,讓它可以在每天00:01自動執(zhí)行,切割昨天的日志(交由awstats分析),壓縮前天的日志(壓縮日志可減小存儲空間,為防止awstats沒有分析完就被壓縮,所以只壓縮前天的日志)。
- vim /server/scripts/cut_nginx_log.sh
輸入以下內(nèi)容:
- #!/bin/sh
- yesterday=`date -d "yesterday" +"%Y%m%d"`
- before_yesterday=`date -d "-2 day" +"%Y%m%d"`
- Nginx_Dir="/usr/local/nginx"
- Nginx_logs="/app/logs"
- Log_Name="www_access"
- cd /tmp
- [ -d $Nginx_Logs ] && cd $Nginx_logs || exit 1
- [ -f $Log_Name.log ] && /bin/mv $Log_Name.log ${Log_Name}_${yesterday}.log || exit 1
- if [ $? -eq 0 -a -f $Nginx_Dir/logs/nginx.pid ]
- then
- kill -USR1 `cat $Nginx_Dir/logs/nginx.pid`
- fi
- [ -f ${Log_Name}_${before_yesterday}.log ] && /usr/bin/gzip ${Log_Name}_${before_yesterday}.log|| exit 1
執(zhí)行crontab -e將該腳本加入定時任務(wù)中
- 1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
這樣每天凌晨00:01就能自動實現(xiàn)日志的切割,壓縮等功能了。
因為本次實驗下的nginx此時已經(jīng)有日志了,另外為了后文awstats能對切割過的日志進行分析,所以這里我們要運行一下此腳本,來將現(xiàn)有日志進行切割生成昨天的日志方便后文操作。
- /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
#p#
二、配置FCGI
1、安裝CPAN
- wget http://search.cpan.org/CPAN/authors/id/A/AN/ANDK/CPAN-2.00.tar.gz
- tar zxf CPAN-2.00.tar.gz
- cd CPAN-2.00
- perl Makefile.PL
- make && make install
2、安裝FCGI和FCGI::ProcManager
- wget http://search.cpan.org/CPAN/authors/id/F/FL/FLORA/FCGI-0.74.tar.gz
- tar zxf FCGI-0.74.tar.gz
- cd FCGI-0.74
- 第一種安裝方法:perl -MCPAN -e 'install FCGI'
- 第二種安裝方法:perl Makefile.PL
- make&&make install
- wget http://search.cpan.org/CPAN/authors/id/B/BO/BOBTFISH/FCGI-ProcManager-0.24.tar.gz
- tar zxf FCGI-ProcManager-0.24.tar.gz
- cd FCGI-ProcManager-0.24
- 第一種安裝方法:perl -MCPAN -e 'install FCGI::ProcManager'
- 第二種安裝方法:perl Makefile.PL
- make&&make install
在執(zhí)行第一種安裝方法的時候,一定是全程自動滾動下來提示OK的。如果出現(xiàn)提示你輸入yes之類的,你需要按提示操作完之后,再運行第二次直到全程自動滾動下來提示OK才為完成安裝?;蛘吣憔陀玫诙N方法來執(zhí)行安裝。
3、創(chuàng)建FCGI啟動文件
- vi /usr/local/nginx/sbin/fcgi #此處按個人習(xí)慣命名
- #!/usr/bin/perl
- use FCGI;
- #perl -MCPAN -e 'install FCGI'
- use Socket;
- use POSIX qw(setsid);
- #use Fcntl;
- require 'syscall.ph';
- &daemonize;
- #this keeps the program alive or something after exec'ing perl scripts
- END() { } BEGIN() { }
- *CORE::GLOBAL::exit = sub { die "fakeexit\nrc=".shift()."\n"; };
- eval q{exit};
- if ($@) {
- exit unless $@ =~ /^fakeexit/;
- };
- &main;
- sub daemonize() {
- chdir '/' or die "Can't chdir to /: $!";
- defined(my $pid = fork) or die "Can't fork: $!";
- exit if $pid;
- setsid or die "Can't start a new session: $!";
- umask 0;
- }
- sub main {
- #$socket = FCGI::OpenSocket( "127.0.0.1:8999", 10 );
- $socket = FCGI::OpenSocket( "/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock", 10 );
- #use UNIX sockets - user running this script must have w access to the 'nginx' folder!!
- $request = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%req_params, $socket );
- if ($request) { request_loop()};
- FCGI::CloseSocket( $socket );
- }
- sub request_loop {
- while( $request->Accept() >= 0 ) {
- #processing any STDIN input from WebServer (for CGI-POST actions)
- $stdin_passthrough ='';
- $req_len = 0 + $req_params{'CONTENT_LENGTH'};
- if (($req_params{'REQUEST_METHOD'} eq 'POST') && ($req_len != 0) ){
- my $bytes_read = 0;
- while ($bytes_read < $req_len) {
- my $data = '';
- my $bytes = read(STDIN, $data, ($req_len - $bytes_read));
- last if ($bytes == 0 || !defined($bytes));
- $stdin_passthrough .= $data;
- $bytes_read += $bytes;
- }
- }
- #running the cgi app
- if ( (-x $req_params{SCRIPT_FILENAME}) && #can I execute this?
- (-s $req_params{SCRIPT_FILENAME}) && #Is this file empty?
- (-r $req_params{SCRIPT_FILENAME}) #can I read this file?
- ){
- pipe(CHILD_RD, PARENT_WR);
- my $pid = open(KID_TO_READ, "-|");
- unless(defined($pid)) {
- print("Content-type: text/plain\r\n\r\n");
- print "Error: CGI app returned no output - Executing $req_params
- {SCRIPT_FILENAME} failed !\n";
- next;
- }
- if ($pid > 0) {
- close(CHILD_RD);
- print PARENT_WR $stdin_passthrough;
- close(PARENT_WR);
- while(my $s = <KID_TO_READ>) { print $s; }
- close KID_TO_READ;
- waitpid($pid, 0);
- } else {
- foreach $key ( keys %req_params){
- $ENV{$key} = $req_params{$key};
- }
- # cd to the script's local directory
- if ($req_params{SCRIPT_FILENAME} =~ /^(.*)\/[^\/]+$/) {
- chdir $1;
- }
- close(PARENT_WR);
- close(STDIN);
- #fcntl(CHILD_RD, F_DUPFD, 0);
- syscall(&SYS_dup2, fileno(CHILD_RD), 0);
- #open(STDIN, "<&CHILD_RD");
- exec($req_params{SCRIPT_FILENAME});
- die("exec failed");
- }
- }
- else {
- print("Content-type: text/plain\r\n\r\n");
- print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is
- not executable by this process.\n";
- }
- }
- }
創(chuàng)建完成后,需要賦予fcgi執(zhí)行權(quán)限:
- chmod 755 /usr/local/nginx/sbin/fcgi
啟動FPM(FastCGI 進程管理器)
- perl /usr/local/nginx/sbin/fcgi >/dev/null 2>$1
在這里,Nginx需要對fcgi生成的/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock有讀寫權(quán)限,否則會報502錯誤。
#p#
三、Awstats的安裝與配置
1、部署awstats
首先我們要下載awstats軟件包,并將其放在常規(guī)目錄(/usr/local)下:
- wget http://awstats.sourceforge.net/files/awstats-7.2.tar.gz
- tar zxf awstats-7.2.tar.gz
- mv awstats-7.2 /usr/local/awstats
由于wget下載下來的包中權(quán)限是非root的,所以這里要修改權(quán)限,否則稍后*.pl將無法運行:
- chown -R root.root /usr/local/awstats
- chmod +x /usr/local/awstats/tools/*.pl
- chmod +x /usr/local/awstats/wwwroot/cgi-bin/*.pl
接下來我們要執(zhí)行awstats/tools下的awstats_configure.pl配置向?qū)?,用來生成awstats的配置文件,awstats配置文件的命名規(guī)則是awstats.website.conf
- cd /usr/local/awstats/tools/
- ./awstats_configure.pl
此時會出現(xiàn)如下提示:
- ----- AWStats awstats_configure 1.0 (build 1.9) (c) Laurent Destailleur -----
- This tool will help you to configure AWStats to analyze statistics for
- one web server. You can try to use it to let it do all that is possible
- in AWStats setup, however following the step by step manual setup
- documentation (docs/index.html) is often a better idea. Above all if:
- - You are not an administrator user,
- - You want to analyze downloaded log files without web server,
- - You want to analyze mail or ftp log files instead of web log files,
- - You need to analyze load balanced servers log files,
- - You want to 'understand' all possible ways to use AWStats...
- Read the AWStats documentation (docs/index.html).
- -----> Running OS detected: Linux, BSD or Unix
- -----> Check for web server install
- Enter full config file path of your Web server.
- Example: /etc/httpd/httpd.conf
- Example: /usr/local/apache2/conf/httpd.conf
- Example: c:\Program files\apache group\apache\conf\httpd.conf
- Config file path ('none' to skip web server setup):
- > none #這里讓填寫網(wǎng)頁服務(wù)器的配置文件路徑,因為我們用的不是apache,所以這里要填none
- Your web server config file(s) could not be found.
- You will need to setup your web server manually to declare AWStats
- script as a CGI, if you want to build reports dynamically.
- See AWStats setup documentation (file docs/index.html)
- -----> Update model config file '/usr/local/awstats/wwwroot/cgi-bin/awstats.model.conf'
- File awstats.model.conf updated.
- -----> Need to create a new config file ?
- Do you want me to build a new AWStats config/profile
- file (required if first install) [y/N] ? y #詢問是否創(chuàng)建一個新的配置文件,這里填y
- -----> Define config file name to create
- What is the name of your web site or profile analysis ?
- Example: www.mysite.com
- Example: demo
- Your web site, virtual server or profile name:
- > www.sunsky.com #這里讓填寫你的網(wǎng)站域名,虛擬主機名或者隨便一個配置名
- -----> Define config file path
- In which directory do you plan to store your config file(s) ?
- Default: /etc/awstats
- Directory path to store config file(s) (Enter for default):
- > #這里要填寫你配置文件存放路徑,我們使用它默認(rèn)的路徑/etc/awstats,所以直接回車即可
- -----> Create config file '/etc/awstats/awstats.www.sunsky.com.conf'
- Config file /etc/awstats/awstats.www.sunsky.com.conf created.
- -----> Add update process inside a scheduler
- Sorry, configure.pl does not support automatic add to cron yet.
- You can do it manually by adding the following command to your cron:
- /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com
- Or if you have several config files and prefer having only one command:
- /usr/local/awstats/tools/awstats_updateall.pl now
- Press ENTER to continue... #提示不能自動加入crontab定時任務(wù),需要稍后自己添加,我們按回車?yán)^續(xù)即可
- A SIMPLE config file has been created: /etc/awstats/awstats.www.sunsky.com.conf
- You should have a look inside to check and change manually main parameters.
- You can then manually update your statistics for 'www.sunsky.com' with command:
- > perl awstats.pl -update -config=www.sunsky.com
- You can also build static report pages for 'www.sunsky.com' with command:
- > perl awstats.pl -output=pagetype -config=www.sunsky.com
- Press ENTER to finish... #提示配置文件創(chuàng)建完成和如何更新配置及建立靜態(tài)報告頁,這里我們回車即可結(jié)束這個配置向?qū)?nbsp;
2、修改awstats配置文件
完成配置文件的創(chuàng)建之后,我們還需要對/etc/awstats/awstats.www.sunsky.com.conf里的一些參數(shù)進行修改。
- sed -i 's#LogFile="/var/log/httpd/mylog.log"#LogFile="/app/logs/www_access_%YYYY-24%MM-24%DD-24.log"#g' /etc/awstats/awstats.www.sunsky.com.conf
這里更改的目的是指定awstats需要分析的nginx的日志文件路徑。這里的路徑大家要按自己的日志路徑來填。
- sed -i 's#DirData="/var/lib/awstats"#DirData="/usr/local/awstats/data"#g'/etc/awstats/awstats.www.sunsky.com.conf
這里更改的目的是指定awstats的數(shù)據(jù)庫配置文件(即awstats的數(shù)據(jù)庫(純文本))。
由于,此處沒有/usr/local/awstats/data目錄,所以我們要創(chuàng)建出來:
- mkdir /usr/local/awstats/data
以上的兩個替換操作進行完之后一定要用命令查看替換是否成功,以便及早發(fā)現(xiàn)紕漏。
- grep "LogFile=" /etc/awstats/awstats.www.sunsky.com.conf
- grep "DirData=" /etc/awstats/awstats.www.sunsky.com.conf
查詢替換結(jié)果正確之后,即可進行下面的步驟。
3、生成awstats統(tǒng)計信息數(shù)據(jù)庫
現(xiàn)在我們需要用awstats來生成對日志的統(tǒng)計分析信息出來了。由于我們用的是支持perl的FCGI動態(tài)化訪問頁面,所以此處我們只需要直接更新數(shù)據(jù)庫即可。FCGI程序會自動將數(shù)據(jù)庫以動態(tài)頁面的形式展現(xiàn)出來,無須再手動生成靜態(tài)頁面了。本處我們用腳本來完成。
- vim /server/scripts/awstats_up.sh
- #!/bin/sh
- /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com >/dev/null 2>&1
該腳本里面用下面的命令也是可以的。
- /usr/local/awstats/tools/awstats_updateall.pl now
運行該腳本生成分析結(jié)果
- /bin/sh /server/scripts/awstats_up.sh
#p#
四、配置日志分析頁面的來訪ip的地址位置顯示
這里我們用國內(nèi)最準(zhǔn)確的ip數(shù)據(jù)庫——QQ純真庫我在博客附件里面放了這個工具,大家下載之后通過CRT用lrzsz工具傳上去,具體步驟這里不寫了。
附件里面有三個文件qqhostinfo.pm,qqwry.pl和QQWry.Dat,我們將這三個文件統(tǒng)統(tǒng)都放到/usr/local/awstats/wwwroot/cgi-bin/plugins中。
接下來,我們修改qqwry.pl文件,將./QQWry.Dat修改為${DIR}/plugins/QQWry
- vim /usr/local/awstats/wwwroot/cgi-bin/plugins/qqwry.pl
- #my $ipfile="./QQWry.Dat";
修改為:
- my $ipfile="${DIR}/plugins/QQWry.Dat ";
然后編輯awstats的配置文件/etc/awstats/awstats.www.sunsky.com.conf(根據(jù)你前面配置的站點信息生成的文件),將LoadPlugin="hostinfo"替換為LoadPlugin="qqhostinfo"即可。
- sed -i 's#\#LoadPlugin="hostinfo"#LoadPlugin="qqhostinfo"#g'/etc/awstats/awstats.www.sunsky.com.conf
切記,在這些替換完之后一定要查看替換是否成功,以便及早發(fā)生紕漏。
- grep "LoadPlugin=\"qqhostinfo\"" /etc/awstats/awstats.www.sunsky.com.conf
如果檢查無誤,那么我們的ip地址位置顯示就配置好了,在后面的日志分析中,我們就可以清楚的看到來訪ip的地理位置信息了。
五、配置nginx
接下來我們要配置nginx使其能安全的訪問到分析的數(shù)據(jù)
- vim /usr/local/nginx/conf/nginx.conf
在server{}內(nèi)添加如下內(nèi)容:
- server {
- listen 80;
- server_name www.sunsky.com;
- location / {
- root /www/sunsky;
- index index.html index.htm;
- access_log /app/logs/www_access.log main;
- }
- location ~* ^/cgi-bin/.*\.pl$ {
- root /usr/local/awstats/wwwroot;
- fastcgi_pass unix:/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock;
- fastcgi_index index.pl;
- include fastcgi_params;
- charset gb2312;
- auth_basic "Restricted"; #有些網(wǎng)站不愿意公開網(wǎng)站流量信息,所以加個認(rèn)證
- auth_basic_user_file /usr/local/nginx/htpasswd.pass; #該文件由apache的加密認(rèn)證工具h(yuǎn)tpasswd創(chuàng)建
- }
- location ~ ^/icon/ {
- root /usr/local/awstats/wwwroot/;
- index index.html;
- access_log off;
- error_log off;
- charset gb2312;
- }
- }
為了保持nginx.conf主配置文件更加整潔干凈,所以我們將fastcgi_param的一系列參數(shù)添加到/usr/local/nginx/conf/fastcgi_params文件的最頂部,然后在nginx.conf里面調(diào)用這個文件即可。
- vi /usr/local/nginx/conf/fastcgi_params
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- fastcgi_param QUERY_STRING $query_string;
- fastcgi_param REQUEST_METHOD $request_method;
- fastcgi_param CONTENT_TYPE $content_type;
- fastcgi_param CONTENT_LENGTH $content_length;
- fastcgi_param GATEWAY_INTERFACE CGI/1.1;
- fastcgi_param SERVER_SOFTWARE nginx;
- fastcgi_param SCRIPT_NAME $fastcgi_script_name;
- fastcgi_param REQUEST_URI $request_uri;
- fastcgi_param DOCUMENT_URI $document_uri;
- fastcgi_param DOCUMENT_ROOT $document_root;
- fastcgi_param SERVER_PROTOCOL $server_protocol;
- fastcgi_param REMOTE_ADDR $remote_addr;
- fastcgi_param REMOTE_PORT $remote_port;
- fastcgi_param SERVER_ADDR $server_addr;
- fastcgi_param SERVER_PORT $server_port;
- fastcgi_param SERVER_NAME $server_name;
- fastcgi_read_timeout 60;
針對上面的加密,由于nginx沒有好的加密認(rèn)證工具,需要借助apache的htpasswd來實現(xiàn)加密認(rèn)證功能:
- htpasswd -c -m /usr/local/nginx/htpasswd.pass sunskyadmin #用戶名為sunskyadmin
配置完畢之后,檢查nginx語法,然后優(yōu)雅重啟之后,用游覽器訪問http://www.sunsky.com/cgi-bin/awstats.pl?config=www.sunsky.com,輸入賬號密碼之后即可查看統(tǒng)計信息了。
至此,awstats已經(jīng)可以實現(xiàn)對Nginx的日志統(tǒng)計,動態(tài)化安全訪問及來訪ip的地址位置顯示等功能了。
五、配置awstats自動運行
為了讓整個日志的統(tǒng)計過程可以實現(xiàn)自動化,將awstats.sh腳本加入crontab定時任務(wù)中去,此時結(jié)合上面的定時切割任務(wù),我們的crontab里面會有多出來兩條定時任務(wù)。
- 1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
- 0 1 * * * /bin/sh /server/scripts/awstats_up.sh >/dev/null 2>&1
到此,我們整個日志訪問工具awstats在nginx上對日志分析之后的靜態(tài)化和動態(tài)化訪問都已經(jīng)實現(xiàn)了。后面的話,我會再寫一篇awstats對apache服務(wù)器的日志分析部署文檔。大家如果有什么問題的話,可以聯(lián)系我進行交流探討,咱們共同學(xué)習(xí),共同進步!
本文作者:sunsky,博客地址:http://sunsky.blog.51cto.com/