欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Nginx日志切割

程序员文章站 2022-03-13 11:52:17
grep生成nginx主配置文件 egrep -v "#|^$" nginx.conf.default >nginx.conf 日志格式 [root@vfast conf]# sed -n '21,23 s/#//gp' nginx.conf.default log_format main '$re ......

grep生成nginx主配置文件

egrep -v "#|^$" nginx.conf.default >nginx.conf

 

日志格式

[root@vfast conf]# sed -n '21,23 s/#//gp' nginx.conf.default 
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

具体配置文件如下:

[root@vfast conf]# cat nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '         配置日志格式
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.blog.conf;
location / {
root html/www;
index index.html index.htm;
}
access_log logs/access_www.log main;       以www.blog.com为例,生成相关的日志文件
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

创建根目录

[root@vfast html]# mkdir www

[root@vfast www]# vim index.html
[root@vfast www]# cat index.html
http://www.blog.com

添加hosts解析

[root@vfast www]# vim /etc/hosts
[root@vfast www]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.31.234 www.blog.com

 

重新加载nginx

[root@vfast www]# /application/nginx/sbin/nginx -s reload

 

测试

[root@vfast www]# curl www.blog.com
http://www.blog.com

 

nginx默认会把所有访问日志生成到access_www.log里,做日志轮询切割,方便日志的分析处理,这里使用按天分割的方法

切割脚本如下:cut_nginx_log.sh

#!/bin/bash

Dateformat=`date +%Y%m%d`
Basedir="/application/nginx"
Nginxlogdir="$Basedir/logs"
Logname="access_www"
[ -d $Nginxlogdir ] && cd $Nginxlogdir||exit 1
[ -f ${Logname}.log ]||exit 1
/bin/mv ${Logname}.log ${Logname}_${Dateformat}.log
$Basedir/sbin/nginx -s reload

 

计划任务实现每天00点整定时执行cut_nginx_log.sh切割日志

 

00 00 * * * /bin/sh /server/script/cut_nginx_logs.sh >/dev/null 2>&1