LAMP--Apache 日志切割

2017-11-02

LAMP--Apache 日志切割

在配置了日志的情况下,我们每访问一次网站,就会记录若干条日志。日志如果不去管理,时间长了日志文件会越来越大,大到不可能用 cat、less 以及 VIM 打开的,head 和 tail 还可以。为了避免产生这么大的日志文件,apache 有相关的配置,使日志按照我们的需求进行归档,比如每天或每小时一个新日志。

[root@localhost ~]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf

打开 apache 的虚拟主机配置文件,可以看到示例配置文件:

#<VirtualHost *:80>
#    ServerAdmin webmaster@dummy-host.example.com
#    DocumentRoot "/usr/local/apache2/docs/dummy-host.example.com"
#    ServerName dummy-host.example.com
#    ServerAlias www.dummy-host.example.com
#    ErrorLog "logs/dummy-host.example.com-error_log"
#    CustomLog "logs/dummy-host.example.com-access_log" common
#</VirtualHost>

其中的 ErrorLog 是错误日志,CustomLog 是访问日志。双引号里的路径是 针对 /usr/local/apache2/ 目录的相对路径,可以通过这段配置设定日志名称,common 是日志的格式。这种方式是固定生成日志的,会造成上面说的日志文件过大,那么我们需要对现有的主机配置做如下操作。

在对应的虚拟主机配置文件中加入 ErrorLog 和 CustomLog 两行:

<VirtualHost *:80>
    DocumentRoot "/data/www"
    ServerName www.123.com
    ServerAlias www.test.com
    ErrorLog "|/usr/local/apache2/bin/rotatelogs -l /usr/local/apache2/logs/123.com-error_%Y%m%d_log 86400"
    CustomLog "|/usr/local/apache2/bin/rotatelogs -l /usr/local/apache2/logs/123.com-access_%Y%m%d_log 86400" combined
  <Directory /data/www/admin.php>
   AllowOverride AuthConfig
   AuthName "Please input the passwd"

双引号中,最前面的竖线就是管道符,意思是把产生的日志传给 rotatelogs ,这个工具是 apache 自带的切割日志的工具。 -l 的作用是校准时区为 UTC,北京时间。最后面的 86400 ,单位是秒,意思是一天。双引号外的 combined 为日志格式,关于日志格式在 /usr/local/apache2/conf/httpd.conf 里面定义。

[root@localhost ~]# grep LogFormat /usr/local/apache2/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 \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio

设定好切割配置后,重启 apache

[root@localhost ~]# /usr/local/apache2/bin/apachectl -t
Syntax OK
[root@localhost ~]# /usr/local/apache2/bin/apachectl restart

用浏览器访问对应网站后,查看日志文件

[root@localhost ~]# ls /usr/local/apache2/logs/
123.com-access_20160518_log         dummy-host.example.com-access_log
access_log                          dummy-host.example.com-error_log
dummy-host2.example.com-access_log  error_log
dummy-host2.example.com-error_log   httpd.pid

已经出现对应日志,更改下时间,再浏览测试一下

[root@localhost ~]# date -s "2016-05-19 09:00:00"
2016年 05月 19日 星期四 09:00:00 CST
[root@localhost ~]# ls /usr/local/apache2/logs/
123.com-access_20160518_log         dummy-host.example.com-access_log
123.com-access_20160519_log         dummy-host.example.com-error_log
access_log                          error_log
dummy-host2.example.com-access_log  httpd.pid
dummy-host2.example.com-error_log

又生成了新的日志文件,切割配置成功。


标题:LAMP--Apache 日志切割
作者:散宜生
地址:https://17kblog.com/articles/2017/11/02/1509585139673.html