首页 > 系统相关 >nginx高级篇之日志切割

nginx高级篇之日志切割

时间:2024-04-07 23:14:11浏览次数:24  
标签:http 切割 -- module nginx 日志 log

一、日志切割(shell脚本)

nginx日志默认是不切割的,网站运行久了自然生成大量日志,导致单文件的处理,太麻烦,因此工作里一般定期切割,一般按天切割。

切割理念

1.给nginx进程发送信号,让nginx生成一个新的日志文件,这就是一个日志切割

2.手动切割,修改日志
准备好旧的日志文件,测试写入大量日志记录
第一种方法,for循环
for num in {1..10000}; do curl 10.0.0.88; done
第二种办法,使用多进程,并发写入的工具,如ab命令,Apache提供的性能压测命令
[root@test-88 ~]#yum install httpd-tools -y

发送10000个http请求,且招来100个人同时发送请求
ab -c 100 -n 10000 http://10.0.0.88/


备份旧日志
cd /var/log/nginx
mv access.log access.log.$(date '+%F')
或者rename log  log.$(date +%F) *.log

生成新日志,给nginx进程发送reopen信号,重新生成新日志
kill -USER1 $(ps -ef | grep 'nginx' |grep 'master' | awk '{print $2}')

shell脚本切割

#!/bin/bash

#源日志目录
logs_path="/var/log/nginx"

#备份日志目录
back_logs_path="${logs_path}/$(date -d 'yesterday' +%F)"

#创建备份目录,以日期格式命名,每天零点切割,开始记录新的日志,备份的目录应该是昨天日期
mkdir -p ${back_logs_path)}

#重命名旧日志,注意日期
cd ${logs_path} && find . -type f | xargs -i mv {} {}.$(date -d 'yesterday' +%F )

#移动旧文件到新建目录下
cd ${logs_path} && find . -type f | xargs -i mv {} ${back_logs_path}
#重新生成新日志
kill -USER1 $(ps -ef | grep 'nginx' |grep 'master' | awk '{print $2}')
或
kill -USER1 `cat /var/run/nginx.pid`

写入定时任务

crontab -e
0 0 * * * /bin/bash 

二、日志切割(logrotate工具)

shell脚本切割比较简单方便、nginx其实提供了更好用的工具
logrotate是一款自动切割日志的工具

1.检查logrotate

# rpm -qa 检查nginx的配置文件列表

[root@web-9 /etc/nginx]#rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params

2.配置解释

[root@web-9 /etc/nginx]#cat /etc/logrotate.d/nginx 
/var/log/nginx/*.log {
        daily                # 每天切割
        missingok            # 忽略错误
        rotate 52            # 最多保留多少个存档    
        compress             # 切割后且压缩
        delaycompress        # 延迟压缩动作在下一次切割
        notifempty           # 日志为空就不切割
        create 640 nginx adm # 切割的文件权限
        sharedscripts        # 共享脚本,结果为空
        postrotate           # 收尾动作,重新生成nginx日志
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript             # 结束动作
}

3.测试切割

[root@test-88 ~]#cat /etc/logrotate.d/nginx 
/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}
[root@test-88 ~]#

写入定时任务,即可按天切割且压缩nginx日志了
[root@test-88 ~]#crontab -l
01 00 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx >> /var/log/nginx/logrotate_nginx.log 2>&1


[root@test-88 ~]#ls /var/log/nginx/
access.log              access.log-20240402.gz  error.log-20240331.gz  error.log-20240407              huoying_81_access.log-20240407
access.log-20240329.gz  access.log-20240403     error.log-20240401.gz  huoying_80_access.log           port_89_error.log
access.log-20240331.gz  error.log               error.log-20240402.gz  huoying_80_access.log-20240407  port_89.log
access.log-20240401.gz  error.log-20240329.gz   error.log-20240403.gz  huoying_81_access.log
[root@test-88 ~]#



三、目录索引、文件下载服务

官网文档
http://nginx.org/en/docs/http/ngx_http_autoindex_module.html

利用nginx实现文件下载服务器

1.参数说明

Syntax:    autoindex on | off;
Default:    
autoindex off;
Context:    http, server, location
# autoindex on   ; 表示开启目录索引
Syntax:    autoindex_localtime on | off;
Default:    
autoindex_localtime off;
Context:    http, server, location

# autoindex_localtime on; 显示文件为服务器的时间
Syntax:    autoindex_exact_size on | off;
Default:    
autoindex_exact_size on;
Context:    http, server, location

# autoindex_exact_size on; 显示确切bytes单位
# autoindex_exact_size off; 显示文件大概单位,是KB、MB、GB

若目录有中文,nginx.conf中添加utf8编码
charset utf-8,gbk;

2.配置文件

测试数据

单独生成子配置文件,专用于下载

重启,查看结果

3.访问目录索引

四、连接数监控

官网文档

http://nginx.org/en/docs/http/ngx_http_stub_status_module.html 模块介绍

该ngx_http_stub_status_module模块提供对基本状态信息的访问。

默认情况下不构建此模块,应使用 --with-http_stub_status_module 配置参数启用它。

Nginx状态信息(status)介绍 Nginx软件在编译时又一个with-http_stub_status_module模块,这个模块功能是记录Nginx的基本访问状态信息,对于想了解nginx的状态以及监控nginx非常有帮助。

让使用者了解Nginx的工作状态。

要想使用状态模块,在编译时必须增加--with-http_stub_status_module参数。

1.参数解释

Active connections
当前活动客户端连接数,包括Waiting连接数。

accepts
接受的客户端连接总数。

handled
处理的连接总数。
accepts 通常,除非已达到某些资源限制(例如, worker_connections限制) ,否则该参数值相同。

requests
客户端请求的总数。

Reading
nginx 正在读取请求标头的当前连接数。

Writing
nginx 将响应写回客户端的当前连接数。

Waiting
当前等待请求的空闲客户端连接数。

# 注意
一个tcp连接,可以发起多个http请求
可以通过修改保持连接参数修改
keepalive_timeout 0; 表示关闭长连接

2.看下你的nginx支持这个模块吗

[root@test-88 ~]#nginx -V
nginx version: nginx/1.24.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

3.配置文件

[root@test-88 ~]#vim /etc/nginx/conf.d/stub_status.conf
[root@test-88 ~]#cat /etc/nginx/conf.d/stub_status.conf
server{
    listen 9999;
    server_name localhost;
  stub_status on;
  access_log off;
}

重启

[root@test-88 ~]#systemctl reload nginx

查看

Ab命令测试连接数

补充说明

ab命令 是一个测试你 Apache http 服务器的工具,你可以通过这个工具,指定一个单位时间内向 apache 发出的请求数量来看看你的 Apache 和机器配合的性能如何。

语法

ab [ -A auth-username:password ] [ -c concurrency ] [ -C cookie-name=value
] [ -d ] [ -e csv-file ] [ -g gnuplot-file ] [ -h ] [ -H custom-header ] [
-i  ]  [  -k  ]  [  -n  requests  ] [ -p POST-file ] [ -P proxy-auth-user‐
name:password ] [ -q ] [ -s ] [ -S ] [ -t timelimit ] [ -T content-type  ]
[  -v verbosity] [ -V ] [ -w ] [ -x <table>-attributes ] [ -X proxy[:port]
]  [  -y  <tr>-attributes  ]  [  -z   <td>-attributes   ]   [http://]host‐
name[:port]/path

选项

-A auth-username:password
    对服务器提供BASIC认证信任。 用户名和密码由一个:隔开,并以base64编码形式发送。 无论服务器是否需要(即, 是否发送了401认证需求代码),此字符串都会被发送。

-c concurrency
    一次产生的请求个数。默认是一次一个。

-C cookie-name=value
    对请求附加一个Cookie:行。 其典型形式是name=value的一个参数对。 此参数可以重复。

-d 显示"percentage served within XX [ms] table"的消息(为以前的版本提供支持)。

-e csv-file
    产生一个以逗号分隔的(CSV)文件, 其中包含了处理每个相应百分比的请求所需要(从1%到100%)的相应百分比的(以微妙为单位)时间。 由于这种格式已经“二进制化”,所以比'gnuplot'格式更有用。

-g gnuplot-file
    把所有测试结果写入一个'gnuplot'或者TSV (以Tab分隔的)文件。 此文件可以方便地导入到Gnuplot, IDL, Mathematica, Igor甚至Excel中。 其中的第一行为标题。

-h 显示使用方法。

-H custom-header
    对请求附加额外的头信息。 此参数的典型形式是一个有效的头信息行,其中包含了以冒号分隔的字段和值的对 (如, "Accept-Encoding: zip/zop;8bit").

-i 执行HEAD请求,而不是GET。

-k 启用HTTP KeepAlive功能,即, 在一个HTTP会话中执行多个请求。 默认时,不启用KeepAlive功能.

-n requests 
    在测试会话中所执行的请求个数。 默认时,仅执行一个请求,但通常其结果不具有代表意义。

-p POST-file
    包含了需要POST的数据的文件.

-P proxy-auth-username:password
    对一个中转代理提供BASIC认证信任。 用户名和密码由一个:隔开,并以base64编码形式发送。 无论服务器是否需要(即, 是否发送了401认证需求代码),此字符串都会被发送。

-q 如果处理的请求数大于150, ab每处理大约10%或者100个请求时,会在stderr输出一个进度计数。 此-q标记可以抑制这些信息。

-s 用于编译中(ab -h会显示相关信息)使用了SSL的受保护的https, 而不是http协议的时候。此功能是实验性的,也是很简陋的。最好不要用。

-S 不显示中值和标准背离值, 而且在均值和中值为标准背离值的1到2倍时,也不显示警告或出错信息。 默认时,会显示 最小值/均值/最大值等数值。(为以前的版本提供支持).

-t timelimit
    测试所进行的最大秒数。其内部隐含值是-n 50000。 它可以使对服务器的测试限制在一个固定的总时间以内。默认时,没有时间限制。

-T content-type
    POST数据所使用的Content-type头信息。

-v verbosity
    设置显示信息的详细程度 - 4或更大值会显示头信息, 3或更大值可以显示响应代码(404, 200等), 2或更大值可以显示警告和其他信息。

-V 显示版本号并退出。

-w 以HTML表的格式输出结果。默认时,它是白色背景的两列宽度的一张表。

-x <table>-attributes
    设置<table>属性的字符串。 此属性被填入<table 这里 >.

-X proxy[:port]
    对请求使用代理服务器。

-y <tr>-attributes
    设置<tr>属性的字符串.

-z <td>-attributes
    设置<td>属性的字符串.

参数

主机:被测试主机。

案例

发送10000个http请求,且招来100个人同时发送请求
[root@test-88 ~]#ab -c 100 -n 10000 http://10.0.0.88/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 10.0.0.88 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        nginx/1.24.0
Server Hostname:        10.0.0.88
Server Port:            80

Document Path:          /
Document Length:        654 bytes

Concurrency Level:      100
Time taken for tests:   0.656 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      8870000 bytes
HTML transferred:       6540000 bytes
Requests per second:    15234.36 [#/sec] (mean)
Time per request:       6.564 [ms] (mean)
Time per request:       0.066 [ms] (mean, across all concurrent requests)
Transfer rate:          13196.17 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.4      1       3
Processing:     2    5   0.6      5       9
Waiting:        0    4   0.4      4       7
Total:          2    7   0.6      6      11
WARNING: The median and mean for the total time are not within a normal deviation
        These results are probably not that reliable.

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      7
  75%      7
  80%      7
  90%      7
  95%      7
  98%      9
  99%     10
 100%     11 (longest request)
[root@test-88 ~]#

标签:http,切割,--,module,nginx,日志,log
From: https://www.cnblogs.com/yechangyao/p/18120129

相关文章

  • Nginx离线配置ssl证书
    纯离线的内网环境中使用nginx配置ssl并使用https访问网站。对于服务器中nginx及其它环境的搭建,可参考我的该文章LinuxCentos7离线部署SpringBoot前后端分离项目同时,该文章涉及的部分安装包已提供在以上文章的开头部分。检查环境进入nginx的安装目录(一般是/usr/lo......
  • nginx日志切割之logrotate
    配置详解logrotate是基于crond服务(定时任务)来运行的,有几个重要的配置:1、/etc/logrotate.conf(主配置)和/etc/logrotate.d/*(子配置)/etc/logrotate.conf是全局配置,logrotate.conf里面包含include/etc/logrotate.d这句,加载子配置文件的意思,说明/etc/logrotate.d/目录下是具体的配......
  • Nginx 文件名逻辑漏洞(CVE-2013-4547)复现
    漏洞原理影响范围:Nginx0.8.41~1.4.3影响范围:Nginx1.5.0~1.5.7Nginx在解析php文件的时候通常在配置文件中如下配置location~\.php${roothtml;includefastcgi_params;fastcgi_passphp:9000;......
  • Nginx 解析漏洞复现
    该漏洞与php和nginx版本无关,是配置错误导致的问题漏洞描述通常在nginx.conf的配置文件或者include包含的其他配置文件下有以下信息location~\.php${fastcgi_indexindex.php;includefastcgi_params;fastcgi_paramR......
  • SpringBoot 日志显示(truncate...),输出完整日志
    本文地址:https://www.cnblogs.com/hchengmx/p/18119562在查看SpringBoot查看日志中,http的responsebody会显示不全,如下:2024-04-0709:39:53.758|172.17.0.8|DEBUG|[qtp1763344271-7365]|org.springframework.core.log.LogFormatUtils.traceDebug(LogFormatUtils.java:119)|Writi......
  • 内网nginx代理高德问题
    A为外网服务器B为内网服务器nginx配置server{listen8081;server_name15.72.185.21; location/webapi/{proxy_passhttp://15.72.191.145:18090/; } location/restapi{ proxy_passhttp://15.72.191.145:18090/restapi/;......
  • 甲方安全建设之日志采集实操干货
    前言没有永远的安全,如何在被攻击的情况下,快速响应和快速溯源分析攻击动作是个重要的话题。想要分析攻击者做了什么、怎么攻击进来的、还攻击了谁,那么日志是必不可少的一项,因此我们需要尽可能采集多的日志来进行分析攻击者的动作,甚至在攻击者刚落脚的时候就阻断攻击者。安装Elast......
  • Nginx日志重定向到标准输出
    背景静态站点使用`docker`部署时,希望`nginx前台启动`的同时可以将错误日志和访问日志全部重定向到标准输出,便于采集和处理!实现只需要修改`nginx.conf`中`3行`关于日志的配置就OK了daemonoff;error_log/dev/stdoutwarn;access_log/dev/stdoutmain;其它配置项保持不变,效果......
  • Nginx 1.25.4 编译安装
    Nginx1.25.4源码编译安装最新长期技术支持版本 nginx-1.25.4,官方下载源码包: https://nginx.org/download/nginx-1.25.4.tar.gz一键安装脚本不啰嗦,脚本简单快速编译安装#!/bin/bash#安装相关包yum-yinstallgccpcre-developenssl-develzlib-develmakewget#......
  • nginx详解
    Nginx安装配置详解Nginx简介Nginx(“enginex”)是一款高性能的Web服务器和反向代理服务器,它采用事件驱动的异步结构,具有内存占用少、稳定性高、能够处理大量的并发请求,具有高效和低资源消耗等特点。Nginx常常被用作Web服务器、负载均衡器、反向代理和缓存服务器等。Nginx安装......