問題:nginx會按照nginx.conf的配置生成access.log和error.log,隨著訪問量的增長,日志文件會越來越大,既會影響訪問的速度(寫入日志時(shí)間延長),也會增加查找日志的難度,nginx沒有這種按天或更細(xì)粒度生成日志的機(jī)制。所以下面介紹兩種方法:1.寫腳本,通過定時(shí)任務(wù)按天重命名日志、重啟nginx的方法實(shí)現(xiàn)(有重啟失敗的風(fēng)險(xiǎn))2.通過工具cronolog實(shí)現(xiàn)。推薦方法二。
1.方法一:創(chuàng)建分割日志文件的腳本,添加定時(shí)任務(wù)
1.1寫腳本:重命名日志文件、重啟nginx
例如存放路徑:/usr/local/nginx/sbin/cut_nginx_logs.sh,按天分割具體內(nèi)容:
#!/bin/bash#function:cut nginx log files#set the path to nginx log fileslog_files_path="/data/nginxlog/"log_files_dir=${log_files_path}#set nginx log files you want to cutlog_files_name=(access )#set the path to nginx.nginx_sbin="/usr/local/nginx/sbin/nginx"#Set how long you want to savesave_days=30#############################################Please do not modify the following script ##############################################mkdir -p $log_files_dirlog_files_num=${#log_files_name[@]}#cut nginx log filesfor((i=0;i<$log_files_num;i++));domv ${log_files_path}${log_files_name[i]}.log ${log_files_dir}${log_files_name[i]}.log_$(date -d "yesterday" +"%Y-%m-%d")done#delete 30 days ago nginx log filesfind $log_files_path -mtime +$save_days -exec rm -rf {} /; #restart nginx$nginx_sbin -s reload1.2.使用crontab添加定時(shí)任務(wù)
//打開定時(shí)任務(wù)crontab -e//進(jìn)入編輯模式i//添加定時(shí)任務(wù)00 00 * * * /bin/sh /usr/local/nginx/sbin/cut_nginx_logs.sh//保存退出:wq!//重啟crontab服務(wù)/etc/init.d/crond restart//查看定時(shí)任務(wù),就會看到你添加的內(nèi)容了crontab -l
2. 方法二:通過cronolog工具實(shí)現(xiàn)
2.1 下載安裝cronolog
2.1.1 下載:下載
2.1.2 安裝
1.解壓縮
# tar zxvf cronolog-1.6.2.tar.gz
2.進(jìn)入安裝文件所在目錄
# cd cronolog-1.6.2
3.運(yùn)行安裝
# ./configure# make# make install
4.查看cronolog安裝后所在目錄(驗(yàn)證安裝是否成功)
# which cronolog
一般情況下顯示為:/usr/local/sbin/cronolog
2.2 使用cronolog
2.2.1.創(chuàng)建命名管道
mkfifo /usr/local/nginx/access_log_pipe
2.2.2 配置cronolog,日期按天
如果按小時(shí)使用access_%Y-%m-%d-%H.log;如果按分鐘使用access_%Y-%m-%d-%H-%M.log
2.2.3 修改配置/usr/local/nginx/conf/nginx.conf
...access_log /usr/local/nginx/access_log_pipe main;...nohup cat /usr/local/nginx/access_log_pipe | /usr/local/sbin/cronolog /usr/local/nginx/logs/access-%Y-%m-%d.log &
新聞熱點(diǎn)
疑難解答
圖片精選