Ubuntu安装 GoAccess 分析 Nginx 日志

对于一个网站而言,网站日志能够反映很多问题,诸如用户访问情况,页面浏览情况,页面命中情况等,可以给我们继续优化网站提供很好的分析支持。

GoAccess 是一个性能优良的网站访问日志开源工具,通过它,我们能以可视化的方式来分析网站日志信息。

下面是在 Ubuntu 上安装 GoAccess 来分析 access.log 文件的一点分享。

安装 GoAccess

  • 使用以下命令安装 GoAccess:

    sudo apt install goaccess
  • 查看 GoAccess 是否安装成功
goaccess -V

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

看到上面的输出信息,说明我们已经安装好了 GoAccess

配置 NginxGoAccess 日志格式

  • 配置 Nginx 日志格式

打开 /etc/nginx/nginx.conf 配置文件,在日志文件下添加如下配置信息:

##
# Logging Settings
##

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

保存 Nginx 配置信息并重启 Nginx

  • 配置 GoAccess 日志格式

打开 GoAccess 配置文件: /etc/goaccess.conf,添加以下配置:

time-format %H:%M:%S
date-format %d/%b/%Y
log-format %h %^ %^ [%d:%t %^] "%r" %s %b "%R" "%u" %^

保存配置文件

分析 access.log 文件并输出为 html 文件

使用以下命令,开始分析 access.log 文件,并输出为 html 文件进行可视化分析:

goaccess access_blog.xsir.com.log -o /home/html/logs/report.html --time-format='%H:%M:%S' --date-format='%d/%b/%y' --log-format=COMBINED --real-time-html
access_blog.xsir.com.log 是需要分析的日志文件,因为我在log文件夹下,所以没有带目录
/home/html/logs/report.html 是输出 html 文件路径
--real-time-html 是实时输出

配置目录查看输出的 html 文件

打开 Nginx 配置文件,在站点配置文件下,添加以下配置信息:

location /report.html {
    alias /home/html/test/report.html;
}

现在我们可以通过访问网站 blog.xsir.com/report.html 查看网站的实时日志

后台运行 GoAccess

我们可以借助 tmux 来使 GoAccess 后台运行:

使用以下命令安装 tmux:

apt install tmux

安装好后,输入以下命令,进入 tmux:

tmux

goaccess access_blog.xsir.com.log -o /home/html/logs/report.html --time-format='%H:%M:%S' --date-format='%d/%b/%y' --log-format=COMBINED --real-time-html

一切正常的话 GoAccess 应该开始分析日志文件了,然后显示 “WebSocket server ready to accept new client connections”。
现在按下你 Tmux 的 PREFIX 键(默认是 Ctrl+B),再按 d 从 Tmux 中脱离出来,这样即使 ssh 断开连接了也能保持后台运行。

想查错也可以用以下命令查看刚才编辑的命令:

tmux attach

更多 GoAccess 使用技巧,参考官网手册。https://goaccess.io/

That's All.