nginx 日志相关配置总结

本文详细介绍了如何在Nginx中配置日志记录,包括设置log_format以记录关键指标如状态码、请求时间和上游响应时间等。此外还讲解了如何使用logrotate进行日志的自动切分和清理。

设置位于nginx.conf:
        log_format  main  '$server_name $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" $upstream_addr $request_time $upstream_response_time';
        access_log /logs/nginx/access.log main;
        error_log /logs/nginx/error.log;
设置可以放在http{}中也可以放在server{}中,后者会针对每个server做不同配置. 
其中最应该关注的除了status,还有request_time 和upstream_response_time有一些细微的差别
request_time官网描述:request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client 。
指的就是从接受用户请求的第一个字节到发送完响应数据的时间,即包括接收请求数据时间、程序响应时间、输出
而真正程序的响应时间应该用$upstream_response_time。
 
 

 
日志自动切分:利用logrotate,首先安装Logrotate,
然后在/etc/logrotate.d 中加入一个文件(注意如果是nginx通过apt-get安装的话该步骤是自动的,所有通过apt-get安装的程序日志都会自动生成logrotate 配置)
 
配置类似于
logs/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        prerotate
                if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                        run-parts /etc/logrotate.d/httpd-prerotate; \
                fi; \
        endscript
        postrotate
                [ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
        endscript
}
 
该配置会按照天来切分.当然最好还要用
/usr/bin/find /logs/nginx -mtime +3 -name "*.log.*" -exec /bin/rm -r {} \;
配置到crontab中定期执行来清理多余的切分文件,否则容易磁盘溢出. 
 

转载于:https://www.cnblogs.com/violinn/p/4940618.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值