nginx日志配置和轮转

一.access_log指令

语法: access_log path [format [buffer=size [flush=time]]];

access_log path format gzip[=level] [buffer=size] [flush=time];

access_log syslog:server=address[,parameter=value] [format];

access_log off;

默认值: access_log logs/access.log combined;

配置段: http, server, location, if in location, limit_except

gzip压缩等级。

buffer设置内存缓存区大小。

flush保存在缓存区中的最长时间。

不记录日志:access_log off;

使用默认combined格式记录日志:access_log logs/access.log 或 access_log logs/access.log combined;

二. log_format指令,设置日志格式

语法: log_format name string …;

默认值: log_format combined “…”;

配置段: http

三.open_log_file_cache指令

语法: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

open_log_file_cache off;

默认值: open_log_file_cache off;

配置段: http, server, location

对于每一条日志记录,都将是先打开文件,再写入日志,然后关闭。可以使用open_log_file_cache来设置日志文件缓存(默认是off),格式如下:

参数注释如下:

max:设置缓存中的最大文件描述符数量,如果缓存被占满,采用LRU算法将描述符关闭。

inactive:设置存活时间,默认是10s

min_uses:设置在inactive时间段内,日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是1次

valid:设置检查频率,默认60s

off:禁用缓存

四. log_not_found指令

语法: log_not_found on | off;

默认值: log_not_found on;

配置段: http, server, location

是否在error_log中记录不存在的错误。默认是。

五.log_subrequest指令

语法: log_subrequest on | off;

默认值: log_subrequest off;

配置段: http, server, location

是否在access_log中记录子请求的访问日志。默认不记录。

六.rewrite_log指令

由ngx_http_rewrite_module模块提供的。用来记录重写日志的。对于调试重写规则建议开启。

语法: rewrite_log on | off;

默认值: rewrite_log off;

配置段: http, server, location, if

启用时将在error log中记录notice级别的重写日志。

七. error_log指令

语法: error_log file | stderr | syslog:server=address[,parameter=value] [debug | info | notice | warn | error | crit | alert | emerg];

默认值: error_log logs/error.log error;

配置段: main, http, server, location

配置错误日志。

error_log 级别分为 debug, info, notice, warn, error, crit 默认为crit, 该级别在日志名后边定义格式如下

八,日志关闭及其他

1.关闭日志

error_log|access_log /dev/null;

2.如果在server段没有设置日志记录方式,那么将会逐步向上去寻找,如果找不到,则使用nginx默认的日志记录方式.

参考:http://www.ttlsa.com/linux/the-nginx-log-configuration/

九.日志按日轮转

在/etc/logrotate.d新建配置文件

/轮转日志目录/*.log {
daily
missingok
rotate 10
dateext
compress
delaycompress
notifempty
sharedscripts
postrotate
kill -USR1 `cat /var/run/nginx.pid`
endscript
}

手动调用(是否轮转取决于是否满足条件):

logrotate /etc/logrotate.d/log-file

模拟调用(不会实际生效,只是模拟):

logrotate -d /etc/logrotate.d/log-file

强制轮转:

logrotate -f /etc/logrotate.d/log-file