日志管理

1、错误日志配置 错误日志属于核心功能模块的参数

worker_processes  1;
error_log  /data/logs/nginx/error.log  error;    #一般配置这一行即可
events {
    worker_connections  1024;
}

语法规则:error_log file level

错误的日志级别有[debug|info|notice|warn|error|crit|alert|emerg],级别越高,记录的信息越少,生产场景一般是warn|error|crit这三个级别之一

可以放置的标签段为:main,http,server,location

2、访问日志配置

①定义日志格式(放置的http标签内),在没有特殊要求的情况下,采用默认配置即可

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

②在每个虚拟主机配置应用

root@c1 ~]# cat /application/nginx/conf/vhost/www.heboan.com.conf
server {
     listen       80;
     server_name  www.heboan.com;
      
     location / {
        root   /data/www/heboan;
        index  index.html index.htm;
     }
     
    access_log  /data/logs/nginx/www.heboan.com.log; #配置这一行即可
}
 
 
#没有什么需求,建议在生产环境关闭访问日志
access_log  off

3、访问日志的轮询切割

①创建轮询切割脚本

#vim /data/shell/nginx_cut_log.sh

#!/bin/bash
#
LOGDIR=/data/logs/nginx
LOGBKDIR=$LOGDIR/`date +%Y-%m`
NGINX_SBIN=/application/nginx/sbin/nginx
 
logrotate () {
    local I
    for I in `ls $LOGDIR`;do
        if [ -f $LOGDIR/$I ];then
            log_bkname=$LOGBKDIR/${I}_`date +%d`.gz
            log_file=$LOGDIR/$I
            cat $log_file|gzip >$log_bkname
            rm -f $I
        fi
    done
    ${NGINX_SBIN} -s reload
}
 
delempdir () {
    local I
    for I in $*;do
        IFEMPTY=`ls $I`
        [ "$IFEMPTY" == "" ] && rmdir $I
    done
}
 
#do the log rotating
[ ! -d $LOGBKDIR ] && mkdir -p $LOGBKDIR
logrotate
 
#delete the outdated bakcup log files
find $LOGDIR -name "*log*" -mtime +7  -exec rm -rf {} \;
 
#delete the empty directory under $LOGDIR
ALLBAKLOCATION=`find $LOGDIR -type d`
delempdir $ALLBAKLOCATION

②通过定时任务每天00.01点准时执行/data/shell/nginx_cut_log.sh

[root@c1 ~]# crontab -l
#cut nginx access log by heboan
01 00 * * * /usr/bin/bash /data/shell/nginx_cut_log.sh

4、不记录不需要的访问日志

在实际工作中,对负载均衡器健康节点检查或某些特定文件(比如图片、js、css)的日志,一般不需要记录下来,因为在统计pv时是按照页面计算的,而日志写入太频繁会消耗大量的I/0,降低服务的性能

具体配置方法如下:

location ~ .*\.(js|png|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
    access_log off;
}

5、访问日志权限设置

加入日志目录为/app/logs,则授权方法如下:

chown -R root.root /app/logs
chmod -R 700 /app/logs

不需要在日志目录上给nginx用户读或写许可,但很多网友都没注意这个问题,他们把该权限直接给了nginx或apache用户,这就成为了安全隐患。

 

posted @ 2017-11-05 16:51  sellsa  阅读(260)  评论(0编辑  收藏  举报