[Apache] 了解访问日志格式设置

你好。
我是系统解决方案部门的宫崎。
在本文中,我将简要介绍 Apache 访问日志的格式化方法。
服务器设置
操作系统版本
[root@Webserver local]# cat /proc/version Linux 版本 4.9.51-10.52.amzn1.x86_64 (mockbuild@gobi-build-64010) (gcc 版本 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC) ) #1 SMP Fri Sep 29 01:16:19 UTC 2017
Apache 版本
[root@localhost]# httpd -v 服务器版本:Apache/2.4.27 (Amazon)
Apache 配置文件位于 /etc/httpd/conf/httpd.conf,具体位置取决于操作系统。
Apache 访问日志输出目标
访问日志的输出目标由 CustomLog 决定。
[root@Webserver ~]# less /etc/httpd/conf/httpd.conf CustomLog "logs/access_log" combined
默认情况下,CustomLog 使用相对路径写入
,该路径表示为相对于“ServerRoot”项的相对路径。
httpd.conf 文件中也写入了“ServerRoot”设置。
[root@Webserver ~]# less /etc/httpd/conf/httpd.conf ServerRoot "/etc/httpd"
换句话说,CustomLog 的位置是
由于它是 ServerRoot/logs/access_log,所以
它变成了 /etc/httpd/logs/access_log。
[root@Webserver ~]# ls -l /etc/httpd/ 总计 12 drwxr-xr-x 2 root root 4096 10月 27 13:36 conf drwxr-xr-x 2 root root 4096 10月 27 13:36 conf.d drwxr-xr-x 2 root root 4096 10月 27 13:36 conf.modules.d lrwxrwxrwx 1 root root 14 10月 27 13:36 logs -> /var/log/httpd lrwxrwxrwx 1 root root 24 10月 27 13:36 modules -> /usr/lib64/httpd/modules lrwxrwxrwx 1 root root 14 10月 27 13:36 run -> /var/run/httpd
/etc/httpd/logs/ 已被 /var/log/httpd 替换,
这意味着访问日志位置为 /var/log/httpd/access_log。
[root@Webserver ~]# ls -l /var/log/httpd 总计 8 -rw-r--r-- 1 root root 1285 10月 27 13:44 access_log -rw-r--r-- 1 root root 1832 10月 27 15:02 error_log
Apache 访问日志格式
Apache 访问日志的格式由 /etc/httpd/conf/httpd.conf 中的 LogFormat 部分决定。
[root@Webserver ~]# less /etc/httpd/conf/httpd.conf LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common
有关自定义日志格式的详细信息,请参阅以下 Apache 官方文档:
http://httpd.apache.org/docs/2.4/mod/mod_log_config.html#formats
LogFormat 的最后一部分,例如“combined”或“common”,称为别名。
昵称也会写入 CustomLog(前面介绍的访问日志的输出目标),并且
具有相同昵称的 LogFormat 格式会输出到访问日志中。
自定义日志“logs/access_log”合并
此自定义日志具有组合别名,
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common
访问日志将以上述 LogFormat 格式输出。
实际上,包含昵称的合并格式访问日志如下所示:
[root@Webserver ~]# less /var/log/httpd/access_log XXX.XXX.XXX.XXX - - [2017年10月27日 04:44:01 +0000] "GET / HTTP/1.1" 403 4891 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
接下来,让我们编辑 /etc/httpd/conf/httpd.conf 中的 CustomLog 和 LogFormat 设置,并查看访问日志。
[root@Webserver ~]# vi /etc/httpd/conf/httpd.conf #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined #LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%h %l %u %t" test #CustomLog "logs/access_log" combined CustomLog "logs/access_log" test
让我们删除 LogFormat 中 %t 之后的所有内容,然后查看昵称设置为 test 的访问日志。
我们会得到什么样的输出?
[root@Webserver ~]# less /var/log/httpd/access_log 200.XXX.XXX.20 - - [27/Oct/2017:05:05:36 +0000]
根据 LogFormat 格式,最多显示 %t,即收到请求的时间。
概括
我一直对访问日志的格式感到疑惑,所以就研究了一下。
我编辑了 httpd.conf 文件,更改了显示的项目,然后
检查了访问日志,这样就更容易理解了。
就是这样。
3