封尘网

让学习成为一种习惯!

让Nginx日志更个性化

日志对于日常工作排错,安全预警非常重要;所以日志分析有利于我们掌握系统的全面信息,本次仅记录关于Nginx的日志配置和切割方法,目前在公司环境中使用的;

nginx有一个非常灵活的日志记录模式。每个级别的配置可以有各自独立的访问日志。
日志格式通过log_format命令来定义。ngx_http_log_module是用来定义请求日志格式的。

  • 默认值: access_log logs/access.log main;
  • 配置段: http, server, location, if in location, limit_except
  • gzip压缩等级。
  • buffer设置内存缓存区大小。
  • flush保存在缓存区中的最长时间。
  • 不记录日志:access_log off;
  • 使用默认main格式记录日志:access_log logs/access.log 或 access_log logs/access.log main;

Nginx默认的访问日志格式:

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

我们自己定义一个proxy名的日志:

log_format  proxy '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" ==> '
                  '$upstream_addr $upstream_response_time [$request_time] ';

仔细看也区别不大;

调用时:

access_log /var/log/nginx/access.log proxy;

相关说明解释:

  • $remote_addr :与$http_x_forwarded_for 用以记录客户端的ip地址;
  • $remote_user :用来记录客户端用户名称;
  • $time_local :用来记录访问时间与时区;(注意,前后必须加上中括号]
  • $request :用来记录请求的url与http协议;
  • $status :用来记录请求状态;成功是200,
  • $body_bytes_sent :记录发送给客户端文件主体内容大小;
  • $http_referer :用来记录从那个页面链接访问过来的;
  • $http_user_agent :记录客户端浏览器的相关信息;
  • $upstream_addr :请求到后端哪个节点上
  • $upstream_response_time :请求程序的响应时间
  • $request_time :响应时间

日志的切割:

#!/bin/bash
# Rotate nginx logs
# Default log name : access.log
# Author : swper

NGX_PID=/var/run/nginx.pid
LOGS_DIR=/var/log/nginx
LOG_NAME=access.log
cd $LOGS_DIR
/bin/mv access.log access_$(date +%F -d -1day).log
/usr/sbin/nginx -s reload

添加定时任务:[每天晚上00:00切割]

00 00 * * * /bin/bash /scripts/rotate-nginx-logs.sh >/dev/null 2>&1

提醒:本文最后更新于 2479 天前,文中所描述的信息可能已发生改变,请谨慎使用。