Nginx日志

错误日志

错误日志是排查错误的依据。它可以配置在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多了参数,即 uriuri+$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表示当切割之后要执行的命令
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值