1、日誌介紹
日誌的配置在nginx.conf中
可以爲每個server配置不同的日誌,如下
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index a.html index.html index.htm;
}
這說明 該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"';
2、自定義一個日誌格式
自定義日誌格式mylog
log_format mylog '$remote_addr- "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
在server中配置mylog
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
access_log logs/mylog.access.log mylog;
location / {
root html;
index a.html index.html index.htm;
}
可以發現mylog.access.log
[root@localhost conf]# curl localhost:80
<html>
<h>welcom visit nginx!!</h>
</html>
[root@localhost conf]# cd ../logs/
[root@localhost logs]# ls
access.log error.log mylog.access.log nginx.pid
[root@localhost logs]# cat mylog.access.log
127.0.0.1- "GET / HTTP/1.1" 200 43 "-" "curl/7.29.0" "-"
3、通過定時任務完成日誌切割
主要目的是實現每天備份一個新的日誌文件
編寫shell腳本
base_path='/usr/local/nginx/logs'
log_path=$(date -d yesterday +"%Y%m")
day=$(date -d yesterday +"%d")
mkdir -p $base_path/$log_path
mv $base_path/mylog.access.log $base_path/$log_path/mylog.access_$day.log
#echo $base_path/$log_path/access_$day.log
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
編寫linux定時任務
crontab -e
每天0點1分執行任務
01 00 * * * sh /usr/local/nginx/logs/runlog.sh
systemctl restart crond
#查看任務
crontab -l
#查看執行日誌
cat /var/log/cron
到了每天0點1分會發現會將之前的日誌打包到一個文件夾內,並打開新的mylog.access.log
附 定時任務表達式說明
* * * * * command
分 時 日 月 周 命令
第1列表示分鐘1~59 每分鐘用*或者 */1表示
第2列表示小時1~23(0表示0點)
第3列表示日期1~31
第4列表示月份1~12
第5列標識號星期0~6(0表示星期天)
第6列要運行的命令
常用表達式
每五分鐘執行 */5 * * * *
每小時執行 0 * * * *
每天執行 0 0 * * *
每週執行 0 0 * * 0
每月執行 0 0 1 * *
每年執行 0 0 1 1 *