goaccessを使用してnginxログを分析する

GoAccessの概要

GoAccessは、インタラクティブなビューインターフェイスを備えたオープンソース(MITライセンス)のリアルタイムWebログ分析ツールで、Webブラウザーまたは* nixシステムのターミナルプログラムからアクセスできます。

これは、システム管理者に高速で価値のあるHTTP統計を提供し、それらをオンラインの視覚化サーバーの形式で提示することができます。GoAccessは、指定されたWebログファイルを解析し、統計結果をX端末に出力します。関数は次のとおりです。

  • 一般統計:このパネルには、有効なリクエストと無効なリクエストの数、これらのデータの分析に費やした時間、独立した訪問者のステータス、リクエストされたファイル、静的ファイル(CSS、ICO、JPGなど)の完全性など、いくつかの主要な指標が表示されます。 URL、404エラー、解析されたログファイルのサイズ、および消費された帯域幅。
  • ユニークビジター:このパネルには、訪問数、ユニークビジター数、および累積帯域幅消費量とその他のインジケーターが日付別に表示されます。同じUserAgent、同じIP、同じアクセス時間のHTTPリクエストは、独立した訪問者として認識されます。Webクローラーはデフォルトで含まれています。
    --date-spec = hrパラメーターを使用して、分析を日付から時間に変更することもできます(例:05 / Jun / 2016:16)。これは、毎日のトラフィックを時間単位で追跡する場合に非常に役立ちます。
  • リクエストされたファイル:このパネルには、サーバー上で最もリクエストされたファイルが表示されます。訪問数、ユニークビジター数、パーセンテージ、累積帯域幅消費、使用されたプロトコル、およびリクエストメソッドを含みます。
  • リクエストされた静的ファイル:JPG、CSS、SWF、JS、GIF、PNGなどの最も頻繁にリクエストされる静的ファイルの種類と、前のパネルのような他のインジケーターをリストします。さらに、静的ファイルを構成ファイルに追加できます。
  • 404またはファイルが見つかりません:表示されるコンテンツは前のパネルと似ていますが、そのデータには、見つからないすべてのページと、一般的に知られている404ステータスコードが含まれます。
  • ホスト:このパネルには、ホスト自体に関する詳細情報が表示されます。これは、悪意のあるクローラーを見つけて、誰が帯域幅を消費しているかを特定するための良い方法です。
    拡張パネルには、ホストの逆DNS解決結果、ホスト国と都市などの詳細情報が表示されます。パラメータが有効な場合、表示するIPアドレスを選択してEnterキーを押すと、UserAgentリストが表示されます。
  • オペレーティングシステム:このパネルには、ホストで使用されているオペレーティングシステムに関する情報が表示されます。GoAccessは、各オペレーティングシステムの詳細情報を提供するために最善を尽くします。
  • ブラウザー:このパネルには、訪問ホストが使用するブラウザー情報が表示されます。GoAccessは、各ブラウザーの詳細情報を提供するために最善を尽くします。
  • 訪問数:このパネルは時間ごとにレポートします。したがって、24のデータポイントが表示され、それぞれが毎日の1時間に対応します。
    --hour-spec = minパラメーターは、10分ごとにレポートするように設定でき、時刻は16:4形式で表示されます。これは、サーバーのピークアクセス期間を検出するのに役立ちます。
  • 仮想ホスト:このパネルには、アクセスログから解析されたさまざまな仮想ホストのステータスが表示されます。このパネルは、ログ形式で%vパラメーターが有効になっている場合にのみ表示されます。
  • 起点URL:問題のホストが他のリソースを介して、および他のホストからのリンクやサイトへのリダイレクトを介してサイトにアクセスする場合、これらの起点URLがこのパネルに表示されます。構成ファイルで、--ignore-panelこの機能をオンにすることができます(デフォルトはオフ)
  • 受信サイト:このパネルには、完全なURLではなく、ホストの一部のみが表示されます。
  • キーワード:レポートでは、Google検索、Googleキャッシュ、Google翻訳でのキーワードの使用がサポートされています。現在、HTTP経由のGoogle検索のみがサポートされています。構成ファイルで、--ignore-panelこの機能をオンにすることができます(デフォルトはオフ)
  • 地理的位置:IPアドレスに基づいて地理的位置を決定します。統計は大陸と国でグループ化されています。地理位置情報モジュールのサポートが必要です。
  • HTTPステータスコード:数値で表されたHTTPリクエストのステータスコード
  • リモートユーザー(HTTP認証)は、HTTP認証を介してドキュメントにアクセスする権限を決定します。ドキュメントがパスワードで保護されていない場合、この部分は「-」と表示されます。このパネルは、パラメーター%eがログ形式変数に設定されていない限り、デフォルトでオンになっています。

GoAccessの使用

goaccessをインストールする

[root@VM_0_26_centos logs]# yum install goaccess
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
epel                                                                | 4.7 kB  00:00:00     
extras                                                              | 2.9 kB  00:00:00     
nux-dextop                                                          | 2.9 kB  00:00:00     
os                                                                  | 3.6 kB  00:00:00     
rpmfusion-free-updates                                              | 3.7 kB  00:00:00     
rpmfusion-nonfree-updates                                           | 3.7 kB  00:00:00     
updates                                                             | 2.9 kB  00:00:00     
zabbix                                                              | 2.9 kB  00:00:00     
zabbix-non-supported                                                |  951 B  00:00:00     
(1/2): epel/7/x86_64/updateinfo                                     | 1.0 MB  00:00:00     
(2/2): epel/7/x86_64/primary_db                                     | 6.9 MB  00:00:02     
Loading mirror speeds from cached hostfile
 * nux-dextop: mirror.li.nux.ro
 * rpmfusion-free-updates: mirrors.ustc.edu.cn
 * rpmfusion-nonfree-updates: mirrors.ustc.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package goaccess.x86_64 0:1.3-1.el7 will be installed
--> Processing Dependency: libtokyocabinet.so.9()(64bit) for package: goaccess-1.3-1.el7.x86_64
--> Running transaction check
---> Package tokyocabinet.x86_64 0:1.4.48-3.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===========================================================================================
 Package                 Arch              Version                   Repository       Size
===========================================================================================
Installing:
 goaccess                x86_64            1.3-1.el7                 epel            240 k
Installing for dependencies:
 tokyocabinet            x86_64            1.4.48-3.el7              os              459 k

Transaction Summary
===========================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 699 k
Installed size: 2.0 M
Is this ok [y/d/N]: y
Downloading packages:
(1/2): goaccess-1.3-1.el7.x86_64.rpm                                | 240 kB  00:00:00     
(2/2): tokyocabinet-1.4.48-3.el7.x86_64.rpm                         | 459 kB  00:00:00     
-------------------------------------------------------------------------------------------
Total                                                      1.3 MB/s | 699 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : tokyocabinet-1.4.48-3.el7.x86_64                                        1/2 
  Installing : goaccess-1.3-1.el7.x86_64                                               2/2 
  Verifying  : tokyocabinet-1.4.48-3.el7.x86_64                                        1/2 
  Verifying  : goaccess-1.3-1.el7.x86_64                                               2/2 

Installed:
  goaccess.x86_64 0:1.3-1.el7                                                              

Dependency Installed:
  tokyocabinet.x86_64 0:1.4.48-3.el7 

使い方を見る

[root@VM_0_26_centos logs]# goaccess -help

GoAccess - 1.3

Usage: goaccess [filename] [ options ... ] [-c][-M][-H][-S][-q][-d][...]
The following options can also be supplied to the command:

Log & Date Format Options

  --date-format=<dateformat>      - Specify log date format. e.g., %d/%b/%Y
  --log-format=<logformat>        - Specify log format. Inner quotes need to be
                                    escaped, or use single quotes.
  --time-format=<timeformat>      - Specify log time format. e.g., %H:%M:%S

User Interface Options

  -c --config-dialog              - Prompt log/date/time configuration window.
  -i --hl-header                  - Color highlight active panel.
  -m --with-mouse                 - Enable mouse support on main dashboard.
  --color=<fg:bg[attrs, PANEL]>   - Specify custom colors. See manpage for more
                                    details and options.
  --color-scheme=<1|2|3>          - Schemes: 1 => Grey, 2 => Green, 3 => Monokai.
  --html-custom-css=<path.css>    - Specify a custom CSS file in the HTML report.
  --html-custom-js=<path.js>      - Specify a custom JS file in the HTML report.
  --html-prefs=<json_obj>         - Set default HTML report preferences.
  --html-report-title=<title>     - Set HTML report page title and header.
  --json-pretty-print             - Format JSON output w/ tabs & newlines.
  --max-items                     - Maximum number of items to show per panel.
                                    See man page for limits.
  --no-color                      - Disable colored output.
  --no-column-names               - Don't write column names in term output.
  --no-csv-summary                - Disable summary metrics on the CSV output.
  --no-html-last-updated          - Hide HTML last updated field.
  --no-parsing-spinner            - Disable progress metrics and parsing spinner.
  --no-progress                   - Disable progress metrics.
  --no-tab-scroll                 - Disable scrolling through panels on TAB.

Server Options

  --addr=<addr>                   - Specify IP address to bind server to.
  --daemonize                     - Run as daemon (if --real-time-html enabled).
  --fifo-in=<path>                - Path to read named pipe (FIFO).
  --fifo-out=<path>               - Path to write named pipe (FIFO).
  --origin=<addr>                 - Ensure clients send the specified origin header
                                    upon the WebSocket handshake.
  --pid-file=<path>               - Write PID to a file when --daemonize is used.
  --port=<port>                   - Specify the port to use.
  --real-time-html                - Enable real-time HTML output.
  --ssl-cert=<cert.crt>           - Path to TLS/SSL certificate.
  --ssl-key=<priv.key>            - Path to TLS/SSL private key.
  --ws-url=<url>                  - URL to which the WebSocket server responds.

File Options

  -                               - The log file to parse is read from stdin.
  -f --log-file=<filename>        - Path to input log file.
  -S --log-size=<number>          - Specify the log size, useful when piping in logs.
  -l --debug-file=<filename>      - Send all debug messages to the specified
                                    file.
  -p --config-file=<filename>     - Custom configuration file.
  --invalid-requests=<filename>   - Log invalid requests to the specified file.
  --no-global-config              - Don't load global configuration file.

Parse Options

  -a --agent-list                 - Enable a list of user-agents by host.
  -b --browsers-file=<path>       - Use additional custom list of browsers.
  -d --with-output-resolver       - Enable IP resolver on HTML|JSON output.
  -e --exclude-ip=<IP>            - Exclude one or multiple IPv4/6. Allows IP
                                    ranges e.g. 192.168.0.1-192.168.0.10
  -H --http-protocol=<yes|no>     - Set/unset HTTP request protocol if found.
  -M --http-method=<yes|no>       - Set/unset HTTP request method if found.
  -o --output=file.html|json|csv  - Output either an HTML, JSON or a CSV file.
  -q --no-query-string            - Ignore request's query string. Removing the
                                    query string can greatly decrease memory
                                    consumption.
  -r --no-term-resolver           - Disable IP resolver on terminal output.
  --444-as-404                    - Treat non-standard status code 444 as 404.
  --4xx-to-unique-count           - Add 4xx client errors to the unique visitors
                                    count.
  --anonymize-ip                  - Anonymize IP addresses before outputting to report.
  --all-static-files              - Include static files with a query string.
  --crawlers-only                 - Parse and display only crawlers.
  --date-spec=<date|hr>           - Date specificity. Possible values: `date`
                                    (default), or `hr`.
  --double-decode                 - Decode double-encoded values.
  --enable-panel=<PANEL>          - Enable parsing/displaying the given panel.
  --hide-referer=<NEEDLE>         - Hide a referer but still count it. Wild cards
                                    are allowed. i.e., *.bing.com
  --hour-spec=<hr|min>            - Hour specificity. Possible values: `hr`
                                    (default), or `min` (tenth of a min).
  --ignore-crawlers               - Ignore crawlers.
  --ignore-panel=<PANEL>          - Ignore parsing/displaying the given panel.
  --ignore-referer=<NEEDLE>       - Ignore a referer from being counted. Wild cards
                                    are allowed. i.e., *.bing.com
  --ignore-statics=<req|panel>    - Ignore static requests.
                                    req => Ignore from valid requests.
                                    panel => Ignore from valid requests and panels.
  --ignore-status=<CODE>          - Ignore parsing the given status code.
  --num-tests=<number>            - Number of lines to test. >= 0 (10 default)
  --process-and-exit              - Parse log and exit without outputting data.
  --real-os                       - Display real OS names. e.g, Windows XP, Snow
                                    Leopard.
  --sort-panel=PANEL,METRIC,ORDER - Sort panel on initial load. For example:
                                    --sort-panel=VISITORS,BY_HITS,ASC. See
                                    manpage for a list of panels/fields.
  --static-file=<extension>       - Add static file extension. e.g.: .mp3.
                                    Extensions are case sensitive.

GeoIP Options

  -g --std-geoip                  - Standard GeoIP database for less memory
                                    consumption.
  --geoip-database=<path>         - Specify path to GeoIP database file. i.e.,
                                    GeoLiteCity.dat, GeoIPv6.dat ...

Other Options

  -h --help                       - This help.
  -V --version                    - Display version information and exit.
  -s --storage                    - Display current storage method. e.g., B+
                                    Tree, Hash.
  --dcf                           - Display the path of the default config
                                    file when `-p` is not used.

Examples can be found by running `man goaccess`.

For more details visit: http://goaccess.io
GoAccess Copyright (C) 2009-2017 by Gerardo Orellana


https://github.com/stockrt/nginx2goaccess/blob/master/nginx2goaccess.shでNginxログ形式変換スクリプトを取得します。具体的な内容は次のとおりです

[root@VM_0_26_centos logs]# cat nginx2goaccess.sh 
#!/bin/bash
#
# Convert from this:
#   http://nginx.org/en/docs/http/ngx_http_log_module.html
# To this:
#   https://goaccess.io/man
#
# Conversion table:
#   $time_local         %d:%t %^
#   $host               %v
#   $http_host          %v
#   $remote_addr        %h
#   $request_time       %T
#   $request_method     %m
#   $request_uri        %U
#   $server_protocol    %H
#   $request            %r
#   $status             %s
#   $body_bytes_sent    %b
#   $bytes_sent         %b
#   $http_referer       %R
#   $http_user_agent    %u
#
# Samples:
#
# log_format combined '$remote_addr - $remote_user [$time_local] '
# '"$request" $status $body_bytes_sent '
# '"$http_referer" "$http_user_agent"';
#   ./nginx2goaccess.sh '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"'
#
# log_format compression '$remote_addr - $remote_user [$time_local] '
# '"$request" $status $bytes_sent '
# '"$http_referer" "$http_user_agent" "$gzip_ratio"';
#   ./nginx2goaccess.sh '$remote_addr - $remote_user [$time_local] "$request" $status $bytes_sent "$http_referer" "$http_user_agent" "$gzip_ratio"'
#
# log_format main
# '$remote_addr\t$time_local\t$host\t$request\t$http_referer\t$http_x_mobile_group\t'
# 'Local:\t$status\t$body_bytes_sent\t$request_time\t'
# 'Proxy:\t$upstream_cache_status\t$upstream_status\t$upstream_response_length\t$upstream_response_time\t'
# 'Agent:\t$http_user_agent\t'
# 'Fwd:\t$http_x_forwarded_for';
#   ./nginx2goaccess.sh '$remote_addr\t$time_local\t$host\t$request\t$http_referer\t$http_x_mobile_group\tLocal:\t$status\t$body_bytes_sent\t$request_time\tProxy:\t$upstream_cache_status\t$upstream_status\t$upstream_response_length\t$upstream_response_time\tAgent:\t$http_user_agent\tFwd:\t$http_x_forwarded_for'
#
# log_format main
# '${time_local}\t${remote_addr}\t${host}\t${request_method}\t${request_uri}\t${server_protocol}\t'
# '${http_referer}\t${http_x_mobile_group}\t'
# 'Local:\t${status}\t*${connection}\t${body_bytes_sent}\t${request_time}\t'
# 'Proxy:\t${upstream_status}\t${upstream_cache_status}\t'
# '${upstream_response_length}\t${upstream_response_time}\t${uri}${log_args}\t'
# 'Agent:\t${http_user_agent}\t'
# 'Fwd:\t${http_x_forwarded_for}';
#   ./nginx2goaccess.sh '${time_local}\t${remote_addr}\t${host}\t${request_method}\t${request_uri}\t${server_protocol}\t${http_referer}\t${http_x_mobile_group}\tLocal:\t${status}\t*${connection}\t${body_bytes_sent}\t${request_time}\tProxy:\t${upstream_status}\t${upstream_cache_status}\t${upstream_response_length}\t${upstream_response_time}\t${uri}${log_args}\tAgent:\t${http_user_agent}\tFwd:\t${http_x_forwarded_for}'
#
# Author: Rogério Carvalho Schneider <[email protected]>

# Params
log_format="$1"

# Usage
if [[ -z "$log_format" ]]; then
    echo "Usage: $0 '<log_format>'"
    exit 1
fi

# Variables map
conversion_table="time_local,%d:%t_%^
host,%v
http_host,%v
remote_addr,%h
request_time,%T
request_method,%m
request_uri,%U
server_protocol,%H
request,%r
status,%s
body_bytes_sent,%b
bytes_sent,%b
http_referer,%R
http_user_agent,%u"

# Conversion
for item in $conversion_table; do
    nginx_var=${item%%,*}
    goaccess_var=${item##*,}
    goaccess_var=${goaccess_var//_/ }
    log_format=${log_format//\$\{$nginx_var\}/$goaccess_var}
    log_format=${log_format//\$$nginx_var/$goaccess_var}
done
log_format=$(echo "$log_format" | sed 's/${[a-z_]*}/%^/g')
log_format=$(echo "$log_format" | sed 's/$[a-z_]*/%^/g')

# Config output
echo "
- Generated goaccess config:
time-format %T
date-format %d/%b/%Y
log_format $log_format
"

# EOF

nginx構成ファイルのlog_formatは次のとおりであり、次の変換は実際の状況と一致している必要があることに注意してください

      log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $upstream_addr $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

ログ形式を取得する

[root@VM_0_26_centos logs]# sh nginx2goaccess.sh '$remote_addr - $remote_user [$time_local] "$request" $status $upstream_addr $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'

- Generated goaccess config:
time-format %T
date-format %d/%b/%Y
log_format %h - %^ [%d:%t %^] "%r" %s %^ %b "%R" "%u" "%^"

ログ形式を設定する

[root@VM_0_26_centos logs]# cat /etc/goaccess/goaccess.conf 
time-format %T
date-format %d/%b/%Y
log_format %h - %^ [%d:%t %^] "%r" %s %^ %b "%R" "%u" "%^"

分析レポートを生成する

[root@VM_0_26_centos logs]# goaccess -f ./nginx_access.log -p ./nginxlog.conf -o day-report.html
[root@VM_0_26_centos logs]# ls
day-report.html      nginx_access.log             nginx2goaccess.sh           nginxlog.conf

レポートパフォーマンス
ブラウザーを開いてday-report.htmlを開くと、効果は次のようになります。
goaccessを使用してnginxログを分析する

おすすめ

転載: blog.51cto.com/jerrymin/2535193