Nginx访问日志
Nginx访问日志
日志格式
1.查看nginx.conf文件
[root@antong ~]# vim /usr/local/nginx/conf/nginx.conf //搜索log_format
log_format test '$remote_addr $http_x_forwarded_for [$time_local]'
' $host "$request_uri" $status'
' "$http_referer" "$http_user_agent"';
$remote_addr | 客户端IP(公网IP) |
---|---|
$http_x_forwarded_for | 代理服务器的IP |
$time_local | 服务器本地时间 |
$host | 访问主机名(域名) |
$request_uri | 访问的url地址 |
$status | 状态码 |
$http_referer | referer |
$http_user_agent | user_agent |
2.定义日志文件
[root@antong ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
server
{
listen 80;
server_name test.com test1.com test2.com;
index index.html index.htm index.php;
root /data/wwwroot/test.com;
if ($host != 'test.com' ) {
rewrite ^/(.*)$ http://test.com/$1 permanent;
}
access_log /tmp/test.com.log test; //分号前面的test是在nginx.conf定义的格式名字
}
[root@antong ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@antong ~]# /usr/local/nginx/sbin/nginx -s reload
3.测试
[root@antong ~]# curl -x127.0.0.1:80 test2.com
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.17.8</center>
</body>
</html>
[root@antong ~]# curl -x127.0.0.1:80 test1.com
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.17.8</center>
</body>
</html>
[root@antong ~]# cat /tmp/test.com.log
127.0.0.1 - [06/Sep/2021:02:57:26 -0400] test2.com "/" 301 "-" "curl/7.29.0"
127.0.0.1 - [06/Sep/2021:02:57:43 -0400] test2.com "/" 301 "-" "curl/7.29.0"
127.0.0.1 - [06/Sep/2021:03:01:37 -0400] test2.com "/" 301 "-" "curl/7.29.0"
127.0.0.1 - [06/Sep/2021:03:01:41 -0400] test1.com "/" 301 "-" "curl/7.29.0"
127.0.0.1 - [06/Sep/2021:03:02:05 -0400] test1.com "/" 301 "-" "curl/7.29.0"
日志切割
因为nginx不像apache自带日志切割的工具,需要借助系统的切割工具和自己写切割脚本
1.创建shell脚本来切割
[root@antong ~]# vim /usr/local/sbin/nginx_log_rotate.sh //脚本文件一般放在这个目录
#! /bin/bash
## 假设nginx的日志存放路径为/data/logs/
d=`date -d "-1 day" +%Y%m%d`
logdir="/data/logs"
nginx_pid="/usr/local/nginx/logs/nginx.pid"
cd $logdir
for log in `ls *.log`
do
mv $log $log-$d
done
/bin/kill -HUP `cat $nginx_pid`
2.查看日志
[root@antong ~]# sh -x /usr/local/sbin/nginx_log_rotate.sh
++ date -d '-1 day' +%Y%m%d
+ d=20210905
+ logdir=/tmp
+ nginx_pid=/usr/local/nginx/logs/nginx.pid
+ cd /tmp
++ ls test.com.log
+ for log in '`ls *.log`'
+ mv test.com.log test.com.log-20210905
++ cat /usr/local/nginx/logs/nginx.pid
+ /bin/kill -HUP 923
[root@antong ~]# ls /tmp/
mysql.sock
pear
php-fcgi.sock
systemd-private-048ae85709794057a15ef8d9867fc1b8-chronyd.service-OdDwEK
systemd-private-c0bc30f50f5147fd8800b9ab1eaabe96-chronyd.service-g5fWDA
test.com.log
test.com.log-20210905
3.清理日志
[root@antong ~]# find /tmp/ -name *.log-* -type f -mtime +7 | xargs rm
//删除七天以上的日志文件