(4)nginx:日志以及定时切割日志小例子
一 關于Nginx日志
我們觀察nginx安裝目錄下的nginx.conf
可以看到如下類似信息
?#access_log? logs/host.access.log? main;
這說明 該server, 它的訪問日志的文件是? logs/host.access.log ,
使用的格式”main”格式.
除了main格式,你可以自定義其他格式.
?
main格式是什么?
log_format? main? '$remote_addr - $remote_user [$time_local]"$request" '
??? #????????????????? '$status $body_bytes_sent"$http_referer" '
??? #????????????????? '"$http_user_agent""$http_x_forwarded_for"';
?
main格式是我們定義好一種日志的格式,并起個名字,便于引用.
以上面的例子, main類型的日志,記錄的 remote_addr.... http_x_forwarded_for等選項.
1: 日志格式 是指記錄哪些選項
默認的日志格式: main
???? log_format? main?'$remote_addr - $remote_user [$time_local] "$request" '
???????????????????????????'$status $body_bytes_sent "$http_referer" '
???? ???????????????????????'"$http_user_agent""$http_x_forwarded_for"';
?
如默認的main日志格式,記錄這么幾項
遠程IP- 遠程用戶/用戶時間 請求方法(如GET/POST) 請求體body長度 referer來源信息
http-user-agent用戶代理/蜘蛛 ,被轉發的請求的原始IP
http_x_forwarded_for:在經過代理時,代理把你的本來IP加在此頭信息中,傳輸你的原始IP
2 配置日志格式小例子
配置如下
訪問后結果
二 日志切割
?切割理由 : 假設一個網站訪問量特別大,每天access_log文件有2個G,如果想從文件中查找一下信息,光打開就很慢了,
? ? ? ? ? ? ? ? ?做日志切割的話,便于維護.
?需求描述 : 為每天的日志新建一個當天文件夾,并將當天文件按每分鐘一個文件放入到相應的文件夾中.
shell腳本(splitLog.sh)編寫如下:
#這里是每分鐘切割一次日志的shell腳本 #!/bin/bash base_path='/usr/local/software/ngnix/install/logs' #定義log基本路徑變量 time=$(date -d yesterday +"%Y-%m-%d_%H-%M-%S" ) #時間定義(格式為 : 2016-10-09_23-46-25) modify_file_name="$time.access.log" #修改的log文件名 today=$(date -d today +"%Y%m%d" ); #今天時間 20161010 today_folder="$base_path/$today"; #今天的文件夾 #如果今天文件夾不存在,則重新創建一個 if [ ! -d "$today_folder" ]; thenmkdir $today_folder fi mv $base_path/access.log $today_folder/$modify_file_name #修改名字 kill -USR1 `cat /usr/local/software/ngnix/install/logs/nginx.pid` #平滑關閉nginx,方便日志切割定時執行該shell ?
?crontab -e 編輯contab命令
*/1 * * * * /usr/local/software/ngnix/install/script/splitLog.sh 指定執行時間
結果圖
總結
以上是生活随笔為你收集整理的(4)nginx:日志以及定时切割日志小例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (3)nginx的虚拟主机配置
- 下一篇: (5) nginx:location