错误日志
错误日志是排查错误的依据。它可以配置在main、http、server、location段里
配置参数格式:error_log /path/to/log level;
level等级的划分:debug | info | notice | warn | error | crit | alert | emerg
越上错误等级越高,不定义等级,默认是error
示例:
error_log /var/log/nginx/error.log crit;
访问日志
格式:
设置日志格式,使用
访问日志是由变量凑成的,定制化程度很高,
日志格式:log_format name ‘变量组’;
先来看看变量
变量 | 说明 |
---|---|
$time_local | 通用日志格式下的本地时间;(服务器时间) |
$remote_addr | 客户端(用户)IP地址 |
$status | 请求状态码,如200,404,301,302等 |
$body_bytes_sent | 发送给客户端的字节数,不包括响应头的大小 |
$bytes_sent | 发送给客户端的总字节数 |
$request_length | 请求的长度(包括请求行,请求头和请求正文) |
$request_time | 请求处理时间,单位为秒,小数的形式 |
$upstream_addr | 集群轮询地址 |
$upstream_response_time | 指从Nginx向后端(php-cgi)建立连接开始到接受完数据然后关闭连接为止的时间 |
$remote_user | 用来记录客户端用户名称 |
$request | 请求方式(GET或者POST等)+URL(包含 r e q u e s t m e t h o d , request_method, requestmethod,host,$request_uri) |
$http_user_agent | 用户浏览器标识 |
$http_host | 请求的url地址(目标url地址)的host |
$http_referer | 来源页面,即从哪个页面转到本页,如果直接在浏览器输入网址来访问,则referer为空 |
$uri | 请求中的当前URI(不带请求参数) |
$document_uri | 等同于$uri |
$request_uri | 比 u r i 多 了 参 数 , 即 uri多了参数,即 uri多了参数,即uri+$args |
$http_x_forwarded_for | 如果使用了代理,这个参数会记录代理服务器的ip和客户端的ip |
示例:
log_format shuai '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
使用:
格式: access_log /path/to/logfile name;
access_log可以配置到http, server, location配置段中。
示例:
server
{
listen 80;
server_name www.shuai.com;
root /data/wwwroot/www.aminglinux.com;
index index.html index.php;
access_log /data/logs/www.shuai.com_access.log shuai;
}
说明:若不指定log_format,则按照默认的格式写日志。
日志记录
静态请求不记录日志
location ~* ^.+\.(gif|jpg|png|css|js)$
{
access_log off;
}
日志切割
shell脚本切割Nginx日志
#!/bin/bash
logdir=/var/log/nginx //定义日志路径
prefix=`date -d "-1 day" +%y%m%d` //定义切割后的日志前缀
cd $logdir
for f in `ls *.log`
do
mv $f $f-$prefix //把日志改名
done
/bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null //生成新的日志
bzip2 *$prefix //压缩日志
find . -type f -mtime +180 |xargs /bin/rm -f //删除超过180天的老日志
系统日志切割机制
在/etc/logrotate.d/下创建nginx文件,内容为:
/data/logs/*log {
daily
rotate 30
missingok
notifempty
compress
sharedscripts
postrotate
/bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null || :
endscript
}
说明:
1 nginx日志在/data/logs/目录下面,日志名字以log结尾
2 daily表示每天切割
3 rotate 30表示日志保留30天
4 missingok表示忽略错误
5 notifempty表示如果日志为空,不切割
6 compress表示压缩
7 sharedscripts和endscript中间可以引用系统的命令
8 postrotate表示当切割之后要执行的命令