본문 바로가기
리눅스

Awstats

by 다움위키 2016. 11. 2.

AWStats - 고급 통계에 대한 무료 로그 파일 분석기:

AWStats는 고급 웹, 스트리밍, FTP 또는 메일 서버에 대한 통계를 그래픽으로 생성해주는 무료로 제공되는 강력하고 특징이 많은 도구입니다. 이 로그 분석기는 CGI 또는 명령 줄에서 작동시킬 수 있고, 몇 가지 그래픽 웹 페이지로 서버 로그에 포함된 모든 가능한 정보를 표시합니다. 게다가 큰 로그 파일을 처리함에 있어 종종 부분적으로 정보를 사용함으로써 빠른 처리를 합니다. 또한 아파치 로그 파일(NCSA combined/XLF/ELF 로그 형식 또는 common/CLF 로그 형식), WebStar, IIS(W3C 로그 형식) 및 다른 많은 웹, 프록시, wap, 스트리밍 서버, 메일 서버 및 몇가지 ftp 서버와 같은 중요한 서버 툴로부터 로그 파일을 분석 가능합니다.

Installation

기본 저장소에 있는 프로그램을 설치합니다. 그리고 각 가상 서버마다 설정 파일을 만들어 줍니다. 여기서는 nginx 서버를 사용합니다.

  • sudo apt-get install awstats
  • cd /etc/awstats
  • sudo ln -sf awstats.conf awstats.localhost.conf
LogFile="/var/log/nginx/access.log"
LogFormat=1
SiteDomain="localhost"
HostAliases="localhost 127.0.0.1"
DNSLookup=1
Lang="ko"

Nginx configuration

서버의 홈페이지가 동작하고 있으므로 awstats는 별도의 위치에 동작하도록 설정합니다. 데비안 패키지에서 제공되는 기본 위치에 맞게 설정을 바꾸어 줍니다.

  • /etc/nginx/site-available/default
	#
	# for awstats
	#
	location ^~ /awstats-icon {
    		alias /usr/share/awstats/icon/;
    		access_log off;
	}
 
	location ^~ /awstatscss {
    		alias /usr/share/doc/awstats/examples/css/;
    		access_log off;
	}
 
	location ^~ /awstatsclasses {
    		alias /usr/share/doc/awstats/examples/classes/;
    		access_log off;
	}
 
	# Configure /cgi-bin/scripts to go through php-fastcgi
	location ~ ^/cgi-bin/.*\.(cgi|pl|py|rb) {
        	gzip off;
        	include         fastcgi_params;
        	fastcgi_pass    unix:/var/run/php5-fpm.sock;
        	fastcgi_index   cgi-bin.php;
        	fastcgi_param   SCRIPT_FILENAME    /etc/nginx/cgi-bin.php;
        	fastcgi_param   SCRIPT_NAME        /cgi-bin/cgi-bin.php;
        	fastcgi_param   X_SCRIPT_FILENAME  /usr/lib$fastcgi_script_name;
        	fastcgi_param   X_SCRIPT_NAME      $fastcgi_script_name;
        	fastcgi_param   REMOTE_USER        $remote_user;
 
        	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 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;
	}
######### http://localhost/awstats/    (rewrite)
        location ~ ^/awstats {
                rewrite ^ http://localhost/cgi-bin/awstats.pl?config=localhost;
        }

아래와 같이 CGI 스크립트를 생성해 줍니다.

  • /etc/nginx/cgi-bin.php
<?php

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")   // stderr is a file to write to
);

$newenv = $_SERVER;
$newenv["SCRIPT_FILENAME"] = $_SERVER["X_SCRIPT_FILENAME"];
$newenv["SCRIPT_NAME"] = $_SERVER["X_SCRIPT_NAME"];

if (is_executable($_SERVER["X_SCRIPT_FILENAME"])) {
    $process = proc_open($_SERVER["X_SCRIPT_FILENAME"], $descriptorspec, $pipes, NULL, $newenv);
    if (is_resource($process)) {
        fclose($pipes[0]);
        $head = fgets($pipes[1]);
        while (strcmp($head, "\n")) {
            header($head);
            $head = fgets($pipes[1]);
        }
        fpassthru($pipes[1]);
        fclose($pipes[1]);
        fclose($pipes[2]);
        $return_value = proc_close($process);
    } else {
        header("Status: 500 Internal Server Error");
        echo("Internal Server Error");
    }
} else {
    header("Status: 404 Page Not Found");
    echo("Page Not Found");
}
?>

이제 웹으로 http://localhost/cgi-bin/awstats.pl?config=localhost 접근하시면 결과를 볼 수 있습니다.
아래쪽의 rewrite를 설정하셨다면, http://localhost/awstats 로 접근하셔도 같은 결과를 얻을 수 있습니다.

Data automatic update

크론 데몬이 10분마다 한번씩 nginx 로그를 읽어들여서 awstats 자료를 갱신하도록 설정해 주도록, /etc/cron.d/awstats를 만듭니다:

*/10 * * * * www-data [ -x /usr/share/awstats/tools/update.sh ] && /usr/share/awstats/tools/update.sh

# Generate static reports:
10 03 * * * www-data [ -x /usr/share/awstats/tools/buildstatic.sh ] && /usr/share/awstats/tools/buildstatic.sh

# data update
*/10 * * * * www-data /usr/lib/cgi-bin/awstats.pl -config=localhost -update > /dev/null

로그 회전 데몬이 하루에 한번씩 쌓인 로그를 압축 저장해 주도록, /etc/logrotate.d/nginx에 수정합니다.

/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        prerotate
                if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                        run-parts /etc/logrotate.d/httpd-prerotate; \
                fi 
                /usr/share/awstats/tools/awstats_buildstaticpages.pl -update -config=localhost -awstatsprog=/usr/lib/cgi-bin/awstats.pl
        endscript
        postrotate
                invoke-rc.d nginx rotate >/dev/null 2>&1
        endscript
}

또는

/var/log/nginx/*.log {
	daily
	rotate 14
	missingok
	compress
	delaycompress
	notifempty
	create 0640 www-data adm
	sharedscripts
	prerotate
		if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
			run-parts /etc/logrotate.d/httpd-prerotate; \
		fi 
		/usr/share/doc/awstats/examples/awstats_updateall.pl now -awstatsprog=/usr/lib/cgi-bin/awstats.pl
	endscript
	postrotate
		invoke-rc.d nginx rotate >/dev/null 2>&1 
	endscript
}

Data manual update

AWStats 설치시에 테스트의 목적 등으로 자료를 수동으로 입력할 수도 있습니다.

  • sudo perl /usr/lib/cgi-bin/awstats.pl -update -config="localhost" -LogFile="/usr/share/awstats/tools/logresolvemerge.pl -dnslookup /var/log/nginx/access.* |"

다른 방법은 다음과 같습니다.

  • sudo /usr/share/doc/awstats/examples/awstats_updateall.pl now -awstatsprog=/usr/lib/cgi-bin/awstats.pl

출력은 다음과 같습니다.

...
Running '"/usr/lib/cgi-bin/awstats.pl" -update -config=localhost -configdir="/etc/awstats"' to update config localhost
Create/Update database for config "/etc/awstats/awstats.localhost.conf" by AWStats version 7.2 (build 1.992)
From data in log file "/var/log/nginx/access.log"...
Phase 1 : First bypass old records, searching new record...
Searching new records from beginning of log file...
Phase 2 : Now process new records (Flush history on disk after 20000 hosts)...
Jumped lines in file: 0
Parsed lines in file: 97
 Found 0 dropped records,
 Found 0 comments,
 Found 0 blank records,
 Found 0 corrupted records,
 Found 92 old records,
 Found 5 new qualified records.

Icon copy

아이콘이 표시되는 페이지와 맞게 아래와 같이 수정해 줍니다.

  • cd /usr/share/awstats/icon/mime
  • sudo rm swf.png flv.png runtime.png conf.png package.png xsl.png document.png
  • sudo cp flash.png swf.png
  • sudo cp flash.png flv.png
  • sudo cp library.png runtime.png
  • sudo cp css.png conf.png
  • sudo cp rar.png package.png
  • sudo cp archive.png archive.bak.png
  • sudo cp rar.png archive.png
  • sudo cp script.png xsl.png
  • sudo cp doc.png document.png

Better AwStats(optional)

AWStats의 자료를 좀더 보기 좋게 표현해 주는 프로그램입니다. 특별한 설정을 안해도 시스템 언어를 인식해서 한글로 표현을 해줍니다.

설정 파일 config.php을 데비안에 맞게 수정해 줍니다.

...
// INFO:    The url of BetterAWstats' directory, No trailing slash
$BAW_CONF['site_url'] = 'https://localhost/betterawstats';
 
// INFO:    The path of BetterAWstats, No trailing slash
$BAW_CONF['site_path'] = '/usr/share/nginx/html/betterawstats';
 
// NAME:    Path to AWStats Data
$BAW_CONF['path_data'] = '/var/lib/awstats';
 
// NAME:    Path to AWStats Libraries
$BAW_CONF['path_lib'] = '/usr/share/awstats/lib';
 
// NAME:    Path to AWStats Language files
$BAW_CONF['path_lang'] = '/usr/share/awstats/lang';
 
// NAME:    URL to AWStats Icons
$BAW_CONF['icons_url'] = 'https://localhost/awstats-icon';
...

기본적인 보안을 위해 암호를 설정해 줍니다.

  • sudo apt install apache2-utils
  • sudo htpasswd -c /etc/nginx/mypasswd 사용자명

Nginx에 설정 /etc/nginx/site-available/default을 아래와 같이 추가해 줍니다.

...
	location /betterawstats {
		auth_basic		"Restricted";
		auth_basic_user_file	/etc/nginx/mypasswd;
		root /usr/share/nginx/html;
		index index.html index.htm index.php;
		location ~ ^/betterawstats/(.+\.php)$ {
			#try_files $uri =404;
			try_files $uri @betterawstatshandler;
			root /usr/share/nginx/html;
			fastcgi_pass unix:/var/run/php5-fpm.sock;
			fastcgi_index index.php;
			fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
			include /etc/nginx/fastcgi_params;
		}
		location ~* ^/betterawstats/(.+\.(gif|jp?eg|png|css|js|cgi|pl|ico|swf|flv|s?html|php|xap|py|xml|txt))$ {
			#access_log        off;
			#log_not_found     off;
			#expires           360d;
			expires 1y;
			root /usr/share/nginx/html;
		}
		#CatchAll - last generates 301 moved permanently
		location ~ ^/betterawstats/.+$ {
			#try_files $uri @betterawstatshandler;
			rewrite ^ /betterawstats last;
		}
	}
	
	location @betterawstatshandler {
		rewrite ^ /betterawstats last;
	}
...

설정이 끝나면 http://localhost/betterawstats 로 접근하셔서 결과를 보실 수 있습니다.

Useful plug-in (optional)

geoip

IP주소에 대한 국가와 도시를 표시하도록 설정해 줄 수 있습니다. 필요한 프로그램을 설치하고, /etc/awstats/awstats.conf 파일을 수정해 줍니다.

  • sudo apt-get install libgeo-ip-perl
LoadPlugin="geoip GEOIP_STANDARD /usr/share/GeoIP/GeoIP.dat"
LoadPlugin="geoip_city_maxmind GEOIP_STANDARD /usr/share/GeoIP/GeoIPCity.dat"

데이터를 가져와서 정해진 위치로 놓습니다. 설정을 바꾸고 나면 항상 해당 서버를 재시작해야 합니다.

Google Chart API plugin

설정에서 다음을 추가합니다:

  • LoadPlugin="graphgooglechartapi"

Rawlog plugin

설정에서 다음을 추가합니다:

  • LoadPlugin="rawlog"

External Resources